2

Edit: This is not a duplicate of NodeJS plans to support import/export es6 (es2015) modules. That question is asking about node's plans. This is a specific technical error now those plans have been implemented. Please read questions before you mark them as duplicate.

Node 12 supports ES modules using the --experimental-modules flag. However when I try to use the import * syntax it fails:

> import * as record from 'src/frontend/rrweb.js'                                                               Thrown:
import * as record from 'src/frontend/rrweb.js'
       ^

SyntaxError: Unexpected token *

Likewise:

import {record} from 'src/frontend/rrweb.js'

Fails with the error SyntaxError: Unexpected token {

Is this a bug or am I doing something wrong? How can I import an ES6 module?

Updates

Loading an .mjs does not work:

$ node --experimental-modules .\deleteme.js                                                  (node:18292) ExperimentalWarning: The ESM module loader is experimental.                                    C:\Users\mikem\Code\appless\deleteme.js:1
import {record} from 'src/frontend/rrweb.mjs'
       ^

SyntaxError: Unexpected token {
mikemaccana
  • 81,787
  • 73
  • 317
  • 396
  • did you try putting it in a file and running `node ./yourFile.js`? – silicakes May 14 '19 at 14:33
  • @silicakes I did that - it executes fine without errors. I;m not sure whether node would use the ES6 syntax to run the module in that case though. – mikemaccana May 14 '19 at 14:38
  • Did you add the `type` field to package.json, or use the `--input-type` cmd flag? – Rengers May 14 '19 at 14:56
  • I'm inclined to agree it is duplicate, because the answer is (likely) the accepted answer in the linked post: you need to set `type: "module"` in the `package.json`. Perhaps its vague though - if that does solve your question maybe its worth making this Q&A specifically making this point. – Meirion Hughes May 14 '19 at 14:56
  • Here's a working solution: https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node apparently you'll need to save your files as `.mjs` – silicakes May 14 '19 at 15:00
  • @MeirionHughes Yes, there is a `package.json` with `"type": "module"` in the same dir as `rrweb.js` – mikemaccana May 14 '19 at 15:06
  • Alas @silicakes `.mjs` doesn't work either. See output above. – mikemaccana May 14 '19 at 15:10
  • works for me™ with `"type": "module"` and `node -v : 12.2.0` and `foo.js` `import {Bar} from './bar.js` and `node --experimental-modules foo.js`. the only caveat is that the import explicitly had to have the file extension; i.e. couldn't find `"./bar"`. I'd suggest sanity checking node version and the flag – Meirion Hughes May 14 '19 at 15:34

0 Answers0