Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
softshipper Avatar asked Jun 10 '18 16:06

softshipper


2 Answers

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.

like image 183
Tsvetan Ganev Avatar answered Sep 24 '22 14:09

Tsvetan Ganev


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.

like image 45
Jose Mato Avatar answered Sep 23 '22 14:09

Jose Mato