Anthony
Anthony

Reputation: 1133

Specifying ES6 modules in Node 12

From my understanding, I can use ES6 imports with Node 12 if I have the line "type": "module" in my package.json file. I'm trying to test this, but I can't get it to work. Anybody know what I'm doing wrong?

My package.json:

{
  "scripts": {
    "run": "clear;clear; node package/index.js",
  },
  "type": "module"
}

and my package/index.js file:

import * as fs from 'fs'

running npm run-script run outputs

import * as fs from 'fs'
       ^

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:718:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
    at internal/main/run_main_module.js:17:11

Upvotes: 3

Views: 2522

Answers (2)

iyhc
iyhc

Reputation: 134

I originally wanted to add comment instead of answer but my reputation is too low to allow me comment. So I place my 'comments' here. Hope everyone understand.

To those who are being directed to this post, here is the most popular Stackoverflow answer. In short, Node 12 is so tricky that it is the only version support ES6 import but requires --experimental-modules flag to run.

I was so confused at first when I see Node12 is supposed to be ES6 compatible but failed in running import statement :(

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122150

Per the documentation and this announcement blog article, for "type": "module" to work you also need to set the --experimental-modules flag when running Node. So in your case the package file script would be:

"run": "clear; clear; node --experimental-modules package/index.js",

Note that this will also enable a warning at startup:

ExperimentalWarning: The ESM module loader is experimental.

Upvotes: 4

Related Questions