使用babel时意外的保留字'import'

在我的NodeJSv4.1.1代码中使用Babel。

得到了要求挂钩在:

require("babel-core/register"); $appRoot = __dirname; module.exports = require("./lib/controllers/app"); 

在随后的lodaded .js文件中,我正在做:

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

但是,这在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) 

听起来就像你没有使用正确的预设。 从babel 6开始,核心babel加载器默认不再包含预期的ES6转换(现在是一个通用的代码转换器平台),您必须使用预置:

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

您还需要安装预设的软件包:

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

看来这个文件没有被转发。 这是随后加载.js文件在node_modules目录? 如果是这样,你需要:

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

默认情况下,所有对node_modules的需求都将被忽略。 您可以通过传递一个忽略正则expression式来覆盖这个

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

我试图通过摩卡运行testing时遇到了问题,我把它解决在我的package.json文件中解决:

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

我不完全清楚这是如何工作的。 我正在运行这样的testing:

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

最终,我想这一切都是有道理的。