Home > Software engineering >  Unexpected identifier: import axios from './lib/axios.js';, require('axios')
Unexpected identifier: import axios from './lib/axios.js';, require('axios')

Time:10-27

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:

  1. Make sure you're using at least [email protected]
  2. Change your run command from 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

CodePudding user response:

What worked for me:

  1. Install curl:

sudo apt install curl

  1. Install NVM:

sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash

  1. List all node versions:

nvm list

  1. Select a node version to use

nvm use v19.0.0

  1. Run the file using:

node test.js

  • Related