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
CodePudding user response:
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.
CodePudding user response:
- Make sure you're using at least [email protected]
- Change your run command from
node test.js
tonode test.js --input-type=module
(This will allow usingimport
in your code)
See the docs: https://nodejs.org/api/packages.html#--input-type-flag
CodePudding user response:
What worked for me:
- Install curl:
sudo apt install curl
- Install NVM:
sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
- List all node versions:
nvm list
- Select a node version to use
nvm use v19.0.0
- Run the file using:
node test.js