javascript - 使用 babel 时出现意外的保留字 'import'

标签 javascript node.js ecmascript-6 babeljs

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

得到了 require 钩子(Hook):

require("babel-core/register");

$appRoot = __dirname;

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

在我正在执行的后续加载的 .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

关于javascript - 使用 babel 时出现意外的保留字 'import',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33710319/

相关文章:

javascript - 目标下一个 sibling 的 child 获得外部高度

javascript - 匹配条件替换字符串

node.js - 为什么我收到 Kafka 错误无法初始化消息中心服务的 SASL 身份验证 : SASL handshake failed when using Node. js 客户端?

javascript - 使用 JWT 在 React 上保护路由

Node.js 原生文件上传表单

javascript - 在 React 中转换对象的对象

javascript - CSS 动画 Onclick

javascript - 图像需要根据第一个 div 图像调整一半大小

javascript - 将旧数组中的新键名称分配给数组

javascript - ES6 const 赋值中的意外行为