In js file, i used import to instead of require
import co from 'co';
And tried to run it directly by nodejs since it said import is 'shipping features' and support without any runtime flag (https://nodejs.org/en/docs/es6/), but i got an error
import co from 'co';
^^^^^^
SyntaxError: Unexpected token import
Then i tried to use babel
npm install -g babel-core
npm install -g babel-cli
npm install babel-core //install to babel locally, is it necessary?
and run by
babel-node js.js
still got same error, unexpected token import?
How could I get rid of it?
babel-core
,babel-polyfill
,babel-preset-es2015
.babelrc
with contents:{ "presets": ["es2015"] }
import
statement in your main entry file, use another file eg:app.js
and your main entry file should requiredbabel-core/register
andbabel-polyfill
to make babel works separately at the first place before anything else. Then you can requireapp.js
whereimport
statement.Example:
index.js
app.js
It should works with
node index.js
.I have done the following to overcome the problem (ex.js script)
problem
solution
It may be that you're running uncompiled files. Let's start clean!
In your work directory create:
A package.json file with the following object:
A file named ".babelrc" with the following instructions:
{"presets": ["latest"]}
Lastly, write test code in your src/index.js file. In your case:
import co from 'co'.
Through your console:
npm install
npm run transpile-es2015
node lib/index.js
next in package.json file add in scripts "start": "babel-node server.js"
and create file for babel , in root ".babelrc"
and run npm start in terminal
From the babel 6 Release notes:
In my setup I installed the es2015 preset
or with yarn
and enabled the preset in my .babelrc
if you use the preset for react-native it accepts the import
and put it inside your .babelrc file
in your project root directory
https://www.npmjs.com/package/babel-preset-react-native