I am trying to use ES6 imports in Node v10.15.3 LTS, but I keep running into the same syntax error. It occurs no matter whether I use esm, babel, or the --experimental-modules flag to enable support for ES6 imports. Here is the error message:

/home/derrick/demo/index.js:1
(function (exports, require, module, __filename, __dirname) { import otherFunction from './otherFunction';
                                                                     ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)

Here is my code (using esm):

package.json

{
  "name": "demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "esm": "^3.2.22"
  }
}

index.js

import otherFunction from './otherFunction';

otherFunction.js

const otherFunction => {
    console.log('Inside other function');
}
export default otherFunction;

I have gone through a couple dozen tutorials trying to figure this out, but I keep getting the same error message.

I've read up on the syntax for imports/exports. I also tried importing { otherFunction } instead of otherFunction, changing the file extensions to .mjs, named vs. default exports, and anything else I can find when I Google this error message.

I am grateful for any suggestions. I've spent 8 hours on this and am about to scream :-)

2 Answers

0
Namhoon Lee On

Because node.js still use common.js module system, you must transpile to use es6 syntax.

To easily run the es6 javascript file, you can install the babel-cli and run it using the babel-node command, as shown below.

npm install -g babel-cli

babel-node index.js
0
Derrick Miller On

I finally got it working with Babel 7, using the instructions at https://hackernoon.com/using-babel-7-with-node-7e401bc28b04 . Here are the basic steps:

  • npm init -y
  • npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
  • npm install --save-dev nodemon
  • Edit .babelrc and change it to { "presets": ["@babel/preset-env"] }
  • nodemon --exec babel-node index.js