Search code examples
javascriptnodes

Can we use "import" keyword when running nodejs v10?


I'm asking if is it possible to use some of new ES features when running node v10, when I tried to use the "import" keywords it throws error:

import  os from 'os';

console.log(os);

when I run it I got:

(function (exports, require, module, __filename, __dirname) { import  os from 'os';
                                                                      ^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)

which ES spec nodejs 10 support ?


Solution

  • You have a few routes. #1, enable experimental module support (Which came in v9), and rename your file with a .mjs extension:

    node --experimental-modules index.mjs
    

    Enable babel transpilation, using babel-node:

    babel-node index.js