Skip to main content
2 of 8
simpler english wording for easy understanding

Wasted about 3 hours.

I just wanted to use the import and export in js files.

Everyone says not possible. But, as of May 2018, it's possible to use above in plain node.js, without any modules like babel, etc.

Here is a simple way to do it.

Create below files, run and see output for yourself.

Also don't forget to see Explanation below.

myfile.mjs

function myFunc() { console.log("Hello from myFunc") } export default myFunc; 

index.mjs

import myFunc from "./myfile" myFunc(); 

run

node --experimental-modules index.mjs 

output

(node:12020) ExperimentalWarning: The ESM module loader is experimental. Hello from myFunc 

Explanation:

  1. Since it is experimental modules, .js files are named .mjs files
  2. While running you will add "--experimental-modules" to the "node index.js"
  3. While running with experimental modules in the output you will see: "(node:12020) ExperimentalWarning: The ESM module loader is experimental. "
  4. I have current release of node js, so if run "node --version", it givese me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS.
  5. Some day in future, you could use .js instead of .mjs, as the features you become stable instead of Experimental.
  6. To use experimental features, see: https://nodejs.org/api/esm.html

Hope that helped.