node.js 运行 mocha 测试时 Babel 意外的令牌导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35040978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Babel unexpected token import when running mocha tests
提问by ThinkingInBits
The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.
其他相关问题中提供的解决方案,例如在 .babelrc 中包含适当的预设 (es2015),已经在我的项目中实现。
I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:
我有两个项目(我们称它们为 A 和 B),它们都使用 ES6 模块语法。在项目 A 中,我正在导入通过 npm 安装并位于 node_modules 文件夹中的项目 B。当我为项目 A 运行测试套件时,出现错误:
SyntaxError: Unexpected token import
语法错误:意外的令牌导入
Which is preceded by this alleged erroneous line of code from Project B:
前面是来自项目 B 的这段所谓的错误代码行:
(function (exports, require, module, __filename, __dirname) { import createBrowserHistory from 'history/lib/createBrowserHistory';
(function (exports, require, module, __filename, __dirname) { import createBrowserHistory from 'history/lib/createBrowserHistory';
The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.
iife 似乎与 npm 或可能与 babel 相关,因为我的源文件仅包含“从 'history/lib/createBrowserHistory' 导入 createBrowserHistory;项目 B 的测试套件中的单元测试运行良好,如果我删除项目 B 作为从项目 A,我的测试套件(仍然使用 es6 导入内部项目模块)工作得很好。
Full Stack Trace:
全栈跟踪:
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Module._extensions..js (module.js:405:10)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (actionCreators.js:4:17)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Here is my test command from package.json:
这是我来自 package.json 的测试命令:
"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"
This StackOverflow post is similar but doesn't offer a solution for my use of the command line: import a module from node_modules with babel but failed
这个 StackOverflow 帖子是类似的,但没有为我使用命令行提供解决方案: 从 node_modules 导入一个模块 babel 但失败
采纳答案by ThinkingInBits
It seems the only solution is to explicitly include:
似乎唯一的解决方案是明确包括:
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
in a test helper file, and pass that along to mocha in my test command:
在测试帮助文件中,并将其传递给我的测试命令中的 mocha:
mocha --require ./test/testHelper.js...
The final solution:
最终的解决方案:
Add registerBabel.js: a separate file whose job is to require babel-core/register...
添加registerBabel.js:一个单独的文件,其工作是需要 babel-core/register ...
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
Add an entry.jsif your application also relies on babel-node. This acts as a wrapper for your es6 containing application.
如果您的应用程序也依赖于 babel-node,请添加entry.js。这充当包含 es6 的应用程序的包装器。
require('./registerBabel');
require('./server'); // this file has some es6 imports
You would then run your application with node entry
然后,您将运行您的应用程序 node entry
For mocha testing, testHelper.jsshould require registerBabel.js as well to initialize babel support at run time.
对于 mocha 测试,testHelper.js 还需要 registerBabel.js 来在运行时初始化 babel 支持。
require('./registerBabel');
And run your mocha tests with mocha --require ./testHelper.js '+(test)/**/*Spec.js'
并运行您的 mocha 测试 mocha --require ./testHelper.js '+(test)/**/*Spec.js'
This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.
这将递归测试“./test”中以“Spec.js”结尾的任何文件。用与您的项目中的规格相匹配的模式替换该模式。
回答by deepelement
For Babel <6
对于巴别塔 <6
The easiest way to solve this problem is:
解决这个问题最简单的方法是:
npm install babel-preset-es2015 --save-devAdd
.babelrcto the root of the project with contents:{ "presets": [ "es2015" ] }
npm install babel-preset-es2015 --save-dev将
.babelrc内容添加到项目的根目录:{ "presets": [ "es2015" ] }
Ensure that you are running mocha with the "--compilers js:babel-core/register" parameter.
确保您使用“--compilers js:babel-core/register”参数运行 mocha。
For Babel6/7+
对于 Babel6/7+
npm install @babel/preset-env --save-devAdd
.babelrcto the root of the project with contents:{ "presets": [ "@babel/preset-env" ] }
npm install @babel/preset-env --save-dev将
.babelrc内容添加到项目的根目录:{ "presets": [ "@babel/preset-env" ] }
Ensure that you are running mocha with the --compilers js:babel-register(Babel 6) or --compilers js:@babel/register(Babel 7) parameter
确保您使用--compilers js:babel-register(Babel 6) 或--compilers js:@babel/register(Babel 7) 参数运行 mocha
For mocha version 7 or later, use --require babel-registeror --require @babel/registerrespectively.
对于 mocha 版本 7 或更高版本,分别使用--require babel-register或--require @babel/register。
回答by Ofir Attal
Well sure you will have that issue, you are using ES6 that mocha don't know
好吧,您肯定会遇到这个问题,您正在使用 mocha 不知道的 ES6
So you are using babel but you don't use it in your test...
所以你正在使用 babel 但你没有在你的测试中使用它......
Few Solutions:
几个解决方案:
A. if you running with NPM use
A. 如果你使用 NPM 运行,请使用
"test": "mocha --compilers js:babel-core/register test*.js"
"test": "mocha --compilers js:babel-core/register test*.js"
B. I'm using
B.我正在使用
"test": "./node_modules/.bin/mocha --compilers js:babel-core/register **/*spec.jsx"
"test": "./node_modules/.bin/mocha --compilers js:babel-core/register **/*spec.jsx"
C. From cli:
C. 来自 cli:
mocha --compilers js:babel-core/register test*.js
mocha --compilers js:babel-core/register test*.js
You can read more at http://www.pauleveritt.org/articles/pylyglot/es6_imports/
您可以在http://www.pauleveritt.org/articles/pylyglot/es6_imports/阅读更多信息
回答by arakno
I ran into that same issue. Having tried every other solution on stackoverflow and beyond, adding this simple config on package.json did it for me:
我遇到了同样的问题。在 stackoverflow 及其他版本上尝试了所有其他解决方案后,在 package.json 上添加这个简单的配置为我做到了:
"babel": {
"presets": [
"es2015"
]
}
All my ES6 imports worked after that. By the way, I had this same configuration inside webpack.config.js, but apparently this was the only way to make it work for mocha testing as well.
在那之后,我所有的 ES6 导入都有效。顺便说一句,我在 webpack.config.js 中有相同的配置,但显然这是使其也适用于 mocha 测试的唯一方法。
Hope this helps someone.
希望这可以帮助某人。
回答by JoeTidee
I had {"modules": false}in my .babelrc file, like so:
我{"modules": false}在我的 .babelrc 文件中,像这样:
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
]
which was throwing
这是扔
Unexpected token import
意外的令牌导入
Once i removed it, mocha ran successfully.
一旦我删除它,摩卡就成功运行了。
回答by Ognyan Dimitrov
I had the same issue and fixed it by reading from the babel documentationfor integrating Babel with Mocha :
我遇到了同样的问题,并通过阅读babel 文档将 Babel 与 Mocha 集成来修复它:
{
"scripts": {
"test": "mocha --compilers js:babel-register"
}
}
回答by syazdani
For anybody using Babel 7 and Mocha 4, some of the package names have changed a bit and the accepted answer is a bit out-dated. What I had to do was:
对于使用 Babel 7 和 Mocha 4 的任何人来说,一些包名称已经发生了一些变化,并且接受的答案有点过时了。我必须做的是:
npm install @babel/register --saveDev
npm install @babel/register --saveDev
and adding --require @babel/registerto the test line in package.json
并添加--require @babel/register到测试行package.json
"test": "./node_modules/mocha/bin/mocha --require @babel/polyfill --require @babel/register './test/**/*.spec.js'"
"test": "./node_modules/mocha/bin/mocha --require @babel/polyfill --require @babel/register './test/**/*.spec.js'"
The @babel/polyfillfixes some things like async/await functionality if you happen to be using those.
该@babel/polyfill修正像异步/ AWAIT功能有些事情,如果你碰巧使用的那些。
Hope that helps somebody :)
希望对某人有所帮助:)
回答by E. Fortes
--compilersis deprecated.
--compilers已弃用。
My simple solution:
我的简单解决方案:
npm install --save-dev babel-core
And in the package.json add your test script like this:
在 package.json 中添加您的测试脚本,如下所示:
"scripts": {
"test": "mocha --require babel-core/register ./test/**/*.js -r ./test-setup.js"
},
回答by pb2q
I'm adding another ES6+mocha+babel config answer here, current as of June '19 (refer to dates on answer/commente). mocha has deprecated the --compilerflag, and the version that I'm using has that unavailable even with --no-deprecationflag, c.f. this
我在这里添加了另一个 ES6+mocha+babel 配置答案,截至 2019 年 6 月(参考答案/评论中的日期)。mocha 已弃用该--compiler标志,而我正在使用的版本即使使用--no-deprecation标志也不可用,请参阅此
Note that I won't include all of the relevant bits from the linked pages, because none of them got me to a clean test build based on the latest versions of mocha and babel; this answer should include the steps that got me to a successful test build.
请注意,我不会包含链接页面中的所有相关部分,因为它们都没有让我基于最新版本的 mocha 和 babel 进行干净的测试构建;这个答案应该包括让我成功进行测试构建的步骤。
Following the instructions here, and in this answer, and here, I tried installing what appeared to be the minimum latest babel using npm install:
按照此处的说明以及此答案和此处的说明,我尝试使用以下方法安装似乎是最低限度的最新 babel npm install:
$ npm install --save-dev mocha
$ npm install --save-dev @babel/preset-env
And I adjusted the mocha invocation in package.json, like so:
我调整了 package.json 中的 mocha 调用,如下所示:
"scripts": {
"test": "mocha --compilers js:@babel/register"
}
This led to errors:
这导致了错误:
× ERROR: --compilers is DEPRECATED and no longer supported.
As above, --no-deprecationdidn't help, please reference the page linked above. So following the instructions from hereI adjusted package.json:
如上所述,--no-deprecation没有帮助,请参考上面链接的页面。所以按照这里的说明我调整了 package.json:
"scripts": {
"test": "mocha --require js:@babel/register"
}
And started seeing errors about locating babel modules, such as:
并开始看到有关定位 babel 模块的错误,例如:
× ERROR: Cannot find module '@babel/register'
At this point I started installing babel packages until I could progress. I believe that the full install is something like:
在这一点上,我开始安装 babel 包,直到我可以进步。我相信完整安装是这样的:
$ npm install --save-dev @babel/preset-env @babel/register @babel/core
The last change required was to update the mocha invocation in package.json, removing the js:prefix, like so:
所需的最后更改是更新 package.json 中的 mocha 调用,删除js:前缀,如下所示:
"scripts": {
"test": "mocha --require @babel/register"
}
I can't answer why this was necessary: if someone can answer this please leave a comment and I'll update my answer with better information.
我无法回答为什么这是必要的:如果有人可以回答这个问题,请发表评论,我会用更好的信息更新我的答案。
The last thing that I did was create a .babelrc in the project directory, with the contents:
我做的最后一件事是在项目目录中创建一个 .babelrc ,内容如下:
{
"presets" : ["@babel/preset-env"]
}
I can't recall what prompted this, but I believethat it was because mocha continued to complain about not recognizing the importkeyword in my test.js. As above, if someone can answer this please leave a comment and I'll update my answer with better information.
我不记得是什么促使了这个,但我相信这是因为 mocha 继续抱怨无法识别import我的 test.js 中的关键字。如上所述,如果有人可以回答这个问题,请发表评论,我会用更好的信息更新我的答案。
回答by productioncoder
Here's what worked for me. I got a warning when using the --compilersflag.
这对我有用。我在使用--compilers标志时收到警告。
DeprecationWarning: "--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSrfor more info
弃用警告:“--compilers”将在 Mocha 的未来版本中删除;有关更多信息,请参阅https://git.io/vdcSr
I therefore replaced it with the --requireflag
因此,我用--require旗帜代替了它
"test": "mocha --require babel-core/register --recursive"
Here's my .babelrc:
这是我的.babelrc:
{
"presets": ["env"]
}
My package.jsondev dependencies
我的package.json开发依赖
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0",
}

