parsecer
parsecer

Reputation: 5106

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

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

Answers (4)

user2959760
user2959760

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

parsecer
parsecer

Reputation: 5106

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

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.
  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

Upvotes: -2

Slbox
Slbox

Reputation: 13128

  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

Upvotes: 0

Quentin
Quentin

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

Related Questions