我正在尝试为使用 ES6 导入语法编写的节点.js应用程序编写一些测试,并使用 rollup.js 将代码连接成一个捆绑包。
为了编写测试,我创建了一个 test
-文件夹,其中包含从我的 src
-文件夹中导入相关部分的代码。我试图在我的 package.json
:
"scripts": {
"test": "mocha ./test/**/*.test.js -r ./test/test_helper.js",
}
这导致代码在我的测试(Unexpected token import
(中抱怨导入语句。当我将 babel-register 包含在测试命令 ( --require babel-register
( 中时,它不再抱怨我的测试文件夹中的导入语句,但它对我的源文件夹中的代码给出了相同的错误:
(function (exports, require, module, __filename, __dirname) { import { Map } from 'immutable';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
...
以下是我的package.json
依赖项:
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015-rollup": "^1.2.0",
"babel-register": "^6.26.0",
"chai": "^3.5.0",
"chai-immutable": "^1.5.4",
"mocha": "^4.1.0",
"redux-node-logger": "0.0.3",
"rollup": "^0.36.0",
"rollup-plugin-babel": "^2.6.1",
"rollup-plugin-json": "^2.0.2"
},
"dependencies": {
"immutable": "^3.8.1",
"mqtt": "^1.9.0",
"redux": "^3.5.2",
"redux-immutable": "^3.0.6"
}
这是我的.babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
使用汇总构建应用程序工作正常。
这是我的rollup.config.js
:
import json from 'rollup-plugin-json';
import babel from 'rollup-plugin-babel';
export default {
entry: 'src/main.js',
format: 'cjs',
plugins: [ json(), babel() ],
external: [
'redux',
'immutable',
'mqtt',
'redux-node-logger',
'http'
],
dest: 'bundle.js'
};
NodeJS还不支持ESModule(只能从命令行进行实验(。所以你需要在CJSModule中转换你的ESModule。你可以用 babel-plugin-transform-es2015-modules-commonjs 插件来做到这一点
在您的 .babelrc 文件中:
"plugins": [
"transform-es2015-modules-commonjs"
]
如果使用 babel-register,则在需要(导入(文件时进行转换
更新
尝试调用require("babel-register")
作为测试套件before
函数的起点。并确保您的路径正确:您不能像在源文件中那样在测试文件中导入immutable
,您需要指定目录src
。或者你可以使用 babel-plugin-module-resolver 将 src 解析为 root
这是我使用.babelrc
文件:
{
"plugins": [
["module-resolver", {
"root": ["./src", "./"]
}],
"transform-es2015-modules-commonjs"
]
}