Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS harmony gives SyntaxError on import

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
like image 925
piggyback Avatar asked Apr 14 '14 21:04

piggyback


People also ask

Why NodeJS Cannot use 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.

Can we use import in NodeJS?

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.

Can I use both import and require in node JS?

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).

What is harmony in node JS?

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.


1 Answers

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.

like image 167
barry-johnson Avatar answered Oct 07 '22 04:10

barry-johnson