softshipper
softshipper

Reputation: 34071

SyntaxError: Unexpected identifier with axios

I am trying to use axios as following:

import axios from 'axios';

axios.post("http://localhost:3000/test", {"prop1": "value"}, {headers: {'X-Custom-Header': 'foobar'}})

then the compiler complains:

/home/developer/Desktop/reason/interoperate/src/Ax.js:1
(function (exports, require, module, __filename, __dirname) { import axios from 'axios';
                                                                     ^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:670:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
developer@monad:~/Desktop/reason/interoperate/src$ node Ax.js
/home/developer/Desktop/reason/interoperate/src/Ax.js:1
(function (exports, require, module, __filename, __dirname) { import axios from 'axios';  

Do I import wrong path?

Upvotes: 6

Views: 22080

Answers (3)

vibhor vaish
vibhor vaish

Reputation: 163

I was also stuck here but I found the answer here : https://github.com/nuxt/docs/issues/42

Since node.js still doesn't support import in official stable release, we should use require keyword. Something like this: const Axios=require('axios');

Of course, do remember to install axios module from npm.

Upvotes: 3

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

Node.js doesn't fully support ES modules yet, which means you cannot use the import keyword. You can use it now with a source code transpiler like Babel and Webpack, but that will require a build step.

Edit: To be fair, Node.js 10.4.0 has an experimental support for ES modules, which is behind a flag: --experimental-modules. This will also require using the .mjs file extension for your JS files.

The feature is currently marked as Stability: 1 - Experimental - Use of the feature is not recommended in production environments.

Upvotes: 10

Jose Mato
Jose Mato

Reputation: 2799

You can make it work with node 10.4.0 in next way:

// Create a file named index.mjs (the extension is the key)

import axios from 'axios';

console.log(axios);

Run it as:

node --experimental-modules index.mjs

But this feature is still experimental, should be avoided in production systems.

Upvotes: 2

Related Questions