Wasted about 3 hours.
I just wanted to use the import and export in jsJavaScript files.
Everyone says it's not possible. But, as of May 2018, it's possible to use above in plain nodeNode.js, without any modules like babelBabel, etc.
Here is a simple way to do it.
Create the below files, run, and see the output for yourself.
Also don't forget to see Explanation below.
myfile.mjs
File myfile.mjs
function myFunc() { console.log("Hello from myFunc") } export default myFunc; index.mjs
File index.mjs
import myFunc from "./myfile.mjs" // simplySimply using "./myfile" may not work in all resolvers myFunc(); run
Run
node --experimental-modules index.mjs output
Output
(node:12020) ExperimentalWarning: The ESM module loader is experimental. Hello from myFunc Explanation:
- Since it is experimental modules, .js files are named .mjs files
- While running you will add
--experimental-modulesto thenode index.mjs - While running with experimental modules in the output you will see: "(node:12020) ExperimentalWarning: The ESM module loader is experimental. "
- I have the current release of node jsNode.js, so if I run
node --version, it gives me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS. - Someday in the future, you could use .js instead of .mjs, as the features become stable instead of Experimental.
- More on experimental features, see: https://nodejs.org/api/esm.html
Hope that helped.