[javascript] "unexpected token import" in Nodejs5 and babel?

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?

This question is related to javascript node.js ecmascript-6 babeljs package.json

The answer is


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


  • 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


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


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/


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.


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


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

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"]
}

  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.


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

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

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


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");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require

Examples related to babeljs

Support for the experimental syntax 'classProperties' isn't currently enabled Export multiple classes in ES6 modules Getting Unexpected Token Export 'import' and 'export' may only appear at the top level Dynamically add child components in React Call async/await functions in parallel Correct way to import lodash Babel command not found ES6 exporting/importing in index file "unexpected token import" in Nodejs5 and babel?

Examples related to package.json

SyntaxError: Cannot use import statement outside a module Module not found: Error: Can't resolve 'core-js/es6' Can not find module “@angular-devkit/build-angular” Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json' Field 'browser' doesn't contain a valid alias configuration How do I add a custom script to my package.json file that runs a javascript file? "unexpected token import" in Nodejs5 and babel? Start script missing error when running npm start How to use private Github repo as npm dependency How to set environment variables from within package.json?