SteinTech
SteinTech

Reputation: 4068

Node doesn't support import/export even if --experimental-modules is set

I am trying to get Node to handle import/export, but I getting syntax errors in the import statement at "import $" -> Unexpected identifier

Node:

node start.js --experimental-modules

start.js:

(() => {
    import $ from "SCRIPT//CommonImport";
});

commonImport.js:

(() => {
    export var $ = require("jquery");
});

package.json:

{
  "type": "module",
  "name": "lc.assets.hyper",
  "version": "1.0.0",
  "description": "brand new UI for LC Assets",
  "main": "start.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Stein Lundbeck",
  "license": "ISC",
  "devDependencies": {
    "jquery": "^3.4.1"
  }
}

Upvotes: 0

Views: 241

Answers (2)

SteinTech
SteinTech

Reputation: 4068

Using the esm module did the trick.

Install:

npm install esm --save-dev

Use:

node -r esm start.js

Upvotes: 0

GProst
GProst

Reputation: 10227

You have to declare all imports at the top of the file like this:

import $ from "/my/path"

And you can't use export statements inside of functions, they have to be declared in the upper scope of your module. And you can't use require (CommonJS) if you're using ES6 import/export, but you can use export ... from ... construction:

export {default as $} from "jquery"

If you want to import modules dynamically you'll have to do it like this:

async function myFunc() {
  const exportedVar = await import('/my/path')
}

Note that import() returns a Promise, i.e. it is async operation, not synchronous as require.

Also note, you can't use export dynamically like import()

Upvotes: 4

Related Questions