Reputation: 5106
I have this js
file:
test.js:
const axios = require('axios');
console.log('test');
I have installed dependencies by running
npm install
My folder structure looks like this:
test
node_modules
package.json
package-lock.json
test.js
If I remove the first line const axios = require('axios');
, and run:
nodejs test.js
it runs fine and prints test
.
However if the first line is present, I get this error:
/home/username/test/node_modules/axios/index.js:1
import axios from './lib/axios.js';
^^^^^
SyntaxError: Unexpected identifier
How do I fix it?
PS
node -v
v18.4.0
nodejs -v
v10.19.0
npm -v
8.12.1
Upvotes: 1
Views: 5100
Reputation: 516
For cases where something went wrong when trying to import a module into a custom or legacy environment, you can try importing the module package directly:
const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
ref https://www.npmjs.com/package/axios#installing
Upvotes: 2
Reputation: 5106
What worked for me:
sudo apt install curl
sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm.
nvm list
nvm use v19.0.0
node test.js
Upvotes: -2
Reputation: 13128
node test.js
to node test.js --input-type=module
(This will allow using import
in your code)See the docs: https://nodejs.org/api/packages.html#--input-type-flag
Upvotes: 0
Reputation: 943635
nodejs test.js
nodejs -v v10.19.0
You are running this with Node 10 which is beyond end of life and does not support ECMAScript modules (with provide import
) except as an experimental feature locked behind a flag.
Use the other version of Node.js you have installed instead.
Upvotes: 2