198

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?

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
johugz
  • 2,023
  • 2
  • 13
  • 9
  • 14
    @FelixKling: Although the answer at the linked question does certainly also answer this question, it's hard to see this question as a duplicate of that one. In any case, I was glad to have this one here, as Google brought me directly here because the described syntax error exactly matched what I saw. I'm honestly glad that the OP posted this rather than searched for a somewhat related question with an answer that happened to fit. – Scott Sauyet Mar 18 '16 at 16:58
  • 3
    `npm i --save-dev babel-cli` Fixed it for me... – ChuckJHardy May 11 '16 at 10:18
  • 2
    I vote to unmark this as a duplicate, I feel this is a separate question. – T.W.R. Cole Jun 27 '16 at 18:09
  • 3
    This is not a duplicate. One other solution I would like to post is to double check you have this plugin in `.babelrc`: `"transform-es2015-modules-commonjs"`. – Dan Dascalescu Nov 08 '16 at 05:36
  • 7
    Duplicates are (should be) ok. It's an important part of how humans work. What @ScottSauyet says is one of the reasons. Different explanations with different perspectives is another. This whole 'duplicate hunt' feels very unhelpful to me as a reguar visitor for years. I wish it would stop. – Stijn de Witt Apr 04 '17 at 14:18
  • For newer versions of react , use the new babel modules : https://stackoverflow.com/a/53927497/6665568 . It has better error messages and supports new features of react. – Natesh bhat Dec 26 '18 at 04:45

13 Answers13

203

From the babel 6 Release notes:

Since Babel is focusing on being a platform for JavaScript tooling and not an ES2015 transpiler, we’ve decided to make all of the plugins opt-in. This means when you install Babel it will no longer transpile your ES2015 code by default.

In my setup I installed the es2015 preset

npm install --save-dev babel-preset-es2015

or with yarn

yarn add babel-preset-es2015 --dev

and enabled the preset in my .babelrc

{
  "presets": ["es2015"]
}
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
  • 14
    Good answer. Unfortunately, you still need to use require() and can't use import for npm packages. – Jagtesh Chadha Dec 01 '15 at 15:22
  • 24
    I use `babel-node` together with `es2015` and `react` presets. Same error. – FuzzY Dec 13 '15 at 22:06
  • 1
    I'm not sure if things have changed in the last few months. But it worked fine for me. – Scott Sauyet Mar 18 '16 at 16:54
  • 3
    Dosn't work. Yes that is needed, but it doesn't make import work. – still_dreaming_1 Aug 11 '16 at 17:52
  • 7
    For me it was a simple fix. I was caught in tunnel vision trying to adapt code from one react/babel project into another es5 project and upgrade to es6 syntax at the same time. In my package.json under scripts, I forgot to replace "node run" with "babel-node run.js". Yeah, I feel sheepish. :) – joezen777 Oct 15 '16 at 14:27
  • npm install babel-preset-latest --save-dev; echo '{ "presets": ["latest"] }' > .babelrc – a0s Nov 25 '16 at 18:27
  • Works as prescribed. Node `v6.2.9`, babel-cli `v6.18.0` – rodrigo-silveira Jan 13 '17 at 21:41
  • For those of you that it doesn't work for, don't forget to install the preset: npm install babel-preset-es2015 --save-dev – omerts Jan 29 '17 at 15:12
  • 1
    sorry, but doesn't work. with `babel-presets-*` installed in devDependencies and `.babelrc` configured to use them – Sylver Feb 18 '17 at 18:42
  • Don't forget to tell them to update babel-preset-es2015. 6.18.0 did not work for me, but 6.24 does – Joe Heyming May 01 '17 at 17:56
  • I know this is going to sound too simple, but if you have tried everything and it still isn't working, double check the spelling of everything. Pretty easy to call it .bablerc, instead of .babelrc of some such mistake! And you will continue to get the “unexpected token import” message. – Craig Gjerdingen Jul 08 '17 at 17:23
  • 2
    JS ecosystem is so easy – Rodrigo Oct 27 '17 at 19:39
52

Until modules are implemented you can use the Babel "transpiler" to run your code:

npm install --save babel-cli babel-preset-node6

and then

./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js

If you dont want to type --presets node6 you can save it .babelrc file by:

{
  "presets": [
    "node6"
  ]
}

See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/

vincent mathew
  • 4,278
  • 3
  • 27
  • 34
  • 16
    latest recommendation from the babel folks is to use [babel-preset-env](https://github.com/babel/babel-preset-env) which detects which polyfills to run, rather than `babel-preset-node*`. In `.babelrc` use: `{ "presets": [ ["env", { "targets": { "node": "current" } }] ] }` – ronen Mar 29 '17 at 13:10
  • After this I started getting the error (unrecognized token '<'): server.js: ```Unexpected token (37:12) 35 | const initialState = store.getState(); 36 | const componentHTML = renderToString( > 37 | | ^ 38 | 39 | , 40 | );``` – A. K. Nov 20 '17 at 13:19
26
  1. Install packages: babel-core, babel-polyfill, babel-preset-es2015
  2. Create .babelrc with contents: { "presets": ["es2015"] }
  3. Do not put import statement in your main entry file, use another file eg: app.js and your main entry file should required babel-core/register and babel-polyfill to make babel works separately at the first place before anything else. Then you can require app.js where import statement.

Example:

index.js

require('babel-core/register');
require('babel-polyfill');
require('./app');

app.js

import co from 'co';

It should works with node index.js.

Adiono
  • 1,034
  • 11
  • 19
  • 1
    This is an easy workaround that can be used for development. Although for production you should always compile your es5 code. – Jonas Jun 08 '17 at 13:29
  • wait... is this what i think it is? a few months ago i had this dream that javascript/perl/any language could be extended without updates by custom extra parsing of the existing language in the same language. Is this what's going on here??? – Dmytro Jul 16 '17 at 10:42
  • Excellent answer. But in the scripts, you can put something like below. So you can use in any file. "scripts": { "build": "babel src -d dist", "start": "node dist/index.js" } – gkarthiks Jul 22 '18 at 01:12
15

babel-preset-es2015 is now deprecated and you'll get a warning if you try to use Laurence's solution.

To get this working with Babel 6.24.1+, use babel-preset-env instead:

npm install babel-preset-env --save-dev

Then add env to your presets in your .babelrc:

{
  "presets": ["env"]
}

See the Babel docs for more info.

kris
  • 23,024
  • 10
  • 70
  • 79
6

if you use the preset for react-native it accepts the import

npm i babel-preset-react-native --save-dev

and put it inside your .babelrc file

{
  "presets": ["react-native"]
}

in your project root directory

https://www.npmjs.com/package/babel-preset-react-native

jde-chil
  • 112
  • 2
  • 4
5

It may be that you're running uncompiled files. Let's start clean!

In your work directory create:

  • Two folders. One for precompiled es2015 code. The other for babel's output. We'll name them "src" and "lib" respectively.
  • A package.json file with the following object:

    { 
      "scripts": {
          "transpile-es2015": "babel src -d lib"
      },
      "devDependencies": {
          "babel-cli": "^6.18.0",
          "babel-preset-latest": "^6.16.0"
      }
    }
    
  • 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:

  • Install your packages: npm install
  • Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json: npm run transpile-es2015
  • Run your code from the output directory! node lib/index.js
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
MarbinJavier
  • 107
  • 1
  • 6
  • Did not work unfortunatley. `Unexpected token import`. – dipole_moment Jun 26 '17 at 18:23
  • 1
    Make sure that the `babel` command is in your search path. Here's a slight variation. `package.json`: { "scripts": { "transpile": "./node_modules/.bin/babel src -d lib" }, "devDependencies": { "babel-cli": "^6.24.1", "babel-preset-env": "^1.6.0" } } `.babelrc`: { "presets": ["env"] } – Maksim Yegorov Jul 21 '17 at 07:36
5

Current method is to use:

npm install --save-dev babel-cli babel-preset-env

And then in in .babelrc

{
    "presets": ["env"]
}

this install Babel support for latest version of js (es2015 and beyond) Check out babeljs

Do not forget to add babel-node to your scripts inside package.json use when running your js file as follows.

"scripts": {
   "test": "mocha",
    //Add this line to your scripts
   "populate": "node_modules/babel-cli/bin/babel-node.js" 
},

Now you can npm populate yourfile.js inside terminal.

If you are running windows and running error internal or external command not recognized, use node infront of the script as follow

node node_modules/babel-cli/bin/babel-node.js

Then npm run populate

Isaac Sekamatte
  • 5,500
  • 1
  • 34
  • 40
3

You have to use babel-preset-env and nodemon for hot-reload.

Then create .babelrc file with below content:

{
  "presets": ["env"]
}

Finally, create script in package.json:

"scripts": {
    "babel-node": "babel-node --presets=env",
    "start": "nodemon --exec npm run babel-node -- ./index.js",
    "build": "babel src -d dist"
  }

Or just use this boilerplate:

Boilerplate: node-es6

Priyanshu Chauhan
  • 5,297
  • 5
  • 35
  • 34
2
  • install --> "npm i --save-dev babel-cli babel-preset-es2015 babel-preset-stage-0"

next in package.json file add in scripts "start": "babel-node server.js"

    {
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "lodash": "^4.17.4",
    "mongoose": "^5.0.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "babel-node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

and create file for babel , in root ".babelrc"

    {
    "presets":[
        "es2015",
        "stage-0"
    ]
}

and run npm start in terminal

lior ben yosef
  • 144
  • 1
  • 6
1

Involve following steps to resolve the issue:

1) Install the CLI and env preset

$ npm install --save-dev babel-cli babel-preset-env

2) Create a .babelrc file

{
  "presets": ["env"]
}

3) configure npm start in package.json

"scripts": {
    "start": "babel-node ./server/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

4) then start app

$ npm start
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
0

I have done the following to overcome the problem (ex.js script)

problem

$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");

$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:152:10)
    at Module._compile (module.js:624:28)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:194:16)
    at bootstrap_node.js:618:3

solution

# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections

# .babelrc setup
$ cat .babelrc
{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported

# or execution with babel-node
$ babel-node ex.js
Successfully Imported
nsaboo
  • 31
  • 4
0

@jovi all you need to do is add .babelrc file like this:

{
  "plugins": [
    "transform-strict-mode",
    "transform-es2015-modules-commonjs",
    "transform-es2015-spread",
    "transform-es2015-destructuring",
    "transform-es2015-parameters"
  ]
}

and install these plugins as devdependences with npm.

then try babel-node ***.js again. hope this can help you.

高建德
  • 57
  • 1
-4

In your app, you must declare your require() modules, not using the 'import' keyword:

const app = require("example_dependency");

Then, create a .babelrc file:

{
"presets": [ 
    ["es2015", { "modules": false }]
]
}

Then, in your gulpfile, be sure to declare your require() modules:

var gulp = require("gulp");
SandPiper
  • 2,816
  • 5
  • 30
  • 52