rcjsdev
rcjsdev

Reputation: 843

Unexpected reserved word 'import' when using babel

Using Babel in my NodeJSv4.1.1 code.

Got the require hook in:

require("babel-core/register");

$appRoot = __dirname;

module.exports = require("./lib/controllers/app");

In a subsequently lodaded .js file I am doing:

import { Strategy as LocalStrategy } from "passport-local";

However this is generating the following error in the CLI:

import { Strategy as LocalStrategy } from "passport-local";
^^^^^^

SyntaxError: Unexpected reserved word
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at loader (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:128:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at module.exports (index.js:9:5)
    at Object.<anonymous> (app.js:102:39)

Upvotes: 27

Views: 34321

Answers (3)

Cameron O&#39;Rourke
Cameron O&#39;Rourke

Reputation: 303

I was hitting the problem when trying to run tests via mocha, and I solved it by putting this in my package.json file:

"babel": {
    "presets": [
      "es2015"
    ]
},

I'm not completely clear on how this works. I'm running tests like this:

mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive

Eventually, this will all make sense I suppose.

Upvotes: 0

Arkadiy Kukarkin
Arkadiy Kukarkin

Reputation: 2293

Sounds like you aren't using the right presets. As of babel 6, the core babel loader no longer includes the expected ES6 transforms by default (it's now a generic code transformer platform), instead you must use a preset:

require('babel-register')({
        "presets": ["es2015"]
});

You will also need to install the preset package:

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

Upvotes: 25

pherris
pherris

Reputation: 17693

It seems that this file is not being transpiled. Is this subsequently loaded .js file in the node_modules directory? If so, you need to:

require("babel-core/register")({
  // This will override `node_modules` ignoring - you can alternatively pass
  // an array of strings to be explicitly matched or a regex / glob
  ignore: false
});

By default all requires to node_modules will be ignored. You can override this by passing an ignore regex

https://babeljs.io/docs/usage/require/

Upvotes: 3

Related Questions