Time is flying and now the Node.js ver.10.0.0 have been out for the public. While I'm working with my MERN stack, frequently I have to switch between ES6 import/export
syntax for the front-end (React.JS) and the CommonJS module.exports/require
syntax in my Node/Express server-side. And I'm really wish the writing style could be unified in import/export
shortly without using Babel and get it from the native support.
A good news is since the last year I read James' post on Medium addressing in the difficulty of implementing the ES6 module system in Node.js, the experimental ECMAScript Modules is now in stability 1 for a while, which means it could be enabled by --experimental-modules
flag.
However, when I'm trying to use import/export
syntax on Node, it is never working. For example, I have try this:
import fs from 'fs';
console.log(typeof fs.readFile);
The above code will throw me error:
(function (exports, require, module, __filename, __dirname) { import fs from 'fs';
^^
SyntaxError: Unexpected identifier
I'm really sure I have enabled the experimental flag calling as $node --experimental-modules
, so what should I really do in order to kick the ES6 import/export
experimental module working on my Node local server? What am I missed?
Added:
The reason why I want to try this experimental feature is to have consistent coding style in both front and back. And because it is now available natively, so I want to get ready to it. Once it have been reach in stage 2, I then can adapted to import/export
quickly and have less pain.
But obviously, Google (ref) and AirBnb(ref) have different view points upon if we should use import/export
syntax or not in their code-style guide. And based on Google, I'm still surprising that the semantics of ES6 import/export is not yet finalized while ECMA2019 is on its way. I'm just wonder when I can really use import/export
in my project, or what is really need to be finalized?
Updated:
After pointed out by Jaromanda X, if I changed my file name to .mjs
then it works. Originally I thought is the module to be loaded have to be named in .mjs
extension, but it seems I was wrong. However, if that is the case, which means I will need to renamed all my project file in .mjs
... and that is not appealing. Just wonder if there is a way to use this feature it in the traditional .js
file? What should I configure?