I was testing node with ES6 with the flag child_process --harmony
but it fails at first step when I import. Any ideas?
import {'spawn'} from child_process;
console.log(spawn);
And i run:
node --harmony test.js
And I get:
:1
(function (exports, require, module, __filename, __dirname) { import {spawn} f
^^^^^^
SyntaxError: Unexpected token import
The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error.
NodeJS allows us to import CommonJS modules from ES Modules. If we would like to import our CommonJS class export example from above, our ES Module import would look like this: // index. mjs import Logger from "./logger.
If nodejs thinks you have a CJS file, you cannot use import (that is only for ESM modules). You can also modify the package. json file that controls your particular script (by adding "type": "module" and force your file to an ESM module if you want (which allows you to use . js files as ESM modules).
As mentioned in the Node Documentation, --harmony flag enables the non stable but tobe soon stabled features of ES6. The current behaviour of the --harmony flag on Node. js is to enable staged features only. After all, it is now a synonym of --es_staging.
Not all features of ES6 are supported in v8 and thus in Node. Modules I believe are one of those things.
You might find this compatibility matrix handy: http://kangax.github.io/es5-compat-table/es6/
You could use the Traceur compiler to do this, although not everything is implemented with modules yet it appears
Edit in Dec 2015 - as some comments to this answer suggest, at this point, Babel has become the preferred ES6 transpiler. At the time I wrote my original answer, Babel was still known as 6to5 and was not as popular as Traceur. Today, Babel is the go-to choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With