ES6 style imports in Node.js REPL

I’m afraid that the answer is no, or at least not yet. We know that it will be supported in the future, but the ES2015 import and export won’t act as in-place substitutions to CommonJS require and module.exports. This is simply because they don’t work the same way. You may find more information in this Node.js blog post and this SO question. In particular, one can already run and import standard modules in Node.js, under the flag --experimental-modules (relevant 2ality blog post). However, this feature will still not work from the REPL.

Your idea of using babel-node (which is now called babel-cli) was not that bad: babel implements an interoperable require function, which is kind of a shim that can retrieve modules designed for either type system. Unfortunately, the official website claims lack of support for this functionality in the REPL:

ES6-style module-loading may not function as expected

Due to technical limitations ES6-style module-loading is not fully supported in a babel-node REPL.

Nonetheless, this issue does not apply to production code, which should not rely on the REPL anyway. Instead of using the REPL, you may consider writing a script in a bare-bones project containing babel-cli, and create a script for running the transpiled version:

{
  "name": "my-test-chamber",
  "private": true,
  "scripts": {
    "build": "babel src/main.js -o lib/main.js",
    "start": "npm run build && node lib/main.js"
  },
  "dev-dependencies": {
    "babel-cli": "^6.0.0"
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)