我的问题不是为什么有些东西不起作用,而是为什么它起作用。是的。
我有一个小型的 nodeJS 命令行工具,其中包含 NodeJS 尚不支持开箱即用的功能,最值得注意的是:
import
声明String.includes()
.因此,为了交付(构建),我转译+捆绑了我的源代码(使用 parcel,就像 webpack 一样)。
作为一个积极的奇迹,我的所有(除了一个)摩卡测试都直接针对我的类而不是捆绑包运行。尽管如此,它们仍然有效!包括许多import
的陈述。并包括“ES6 自测试”:
it( 'String - include', () => {
var s = 'Southern Bananas'
assert( s.includes( 'anana' ) )
assert( !s.includes( 'kiwi' ) )
} )
##因此: 我的测试代码
中有 String.includes,而不仅仅是在被测试的源代码中。而且没有地方可以转译或捆绑我的测试代码......因此对我的愚蠢问题表示歉意: 为什么这有效?某处是否有秘密的即时编译? (如果是的话,我也可以将其用于我的可交付测试代码的调试风格吗?)
mocha.opts
相当简单:
--require @babel/register
--require ./test/once.js (nothing special here, either)
--reporter list
--recursive
我的
.babelrc
有这个:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"Electron": "3.0",
"Node": "8.0"
}
}
]
],
"plugins": [
"@babel/plugin-transform-runtime"
],
"retainLines": true,
"comments": false,
"sourceMaps": true
}
@babel/plugin-transform-runtime
显然不是要
责备赞扬,因为它
@babel/polyfill
是否包含在
简约现代据我所知
@babel/preset-env
中?我还做对了什么:+)?有没有办法将这个实时编译也用于我的(调试)构建?String.prototype.includes
。
@babel/register
导致您的代码被动态编译,这就是您的 import
语句起作用的原因。我怀疑你需要 @babel/plugin-transform-runtime
插件,除非我错过了你想要实现的目标。什么会导致这种混乱?
Babel 作者让该工具变得
为什么
String.prototype.includes
这个有更简单的解释。
String.prototype.includes
早在 Node.js v6.5 就已经得到原生支持(
如您所见,从该版本开始就支持绝大多数 ES2015)。 因此,虽然您没有配置
@babel/polyfill
(据我所知)并且您
在不支持String.prototype.includes
的环境中需要它,但您的环境已经支持! 来自 Node.js v8.x REPL:
> 'ES2015'.includes('2015')
true
为什么你的
import
正如您所说,Node.js v8.x
。然而,有一些关于如何将其作为实验性功能启用的好文章从 Node.js v9.x 开始。 因此,您可以使用本机 Node.js v8.x(通过 REPL)获得以下内容:
> import path from 'path';
import path from 'path';
^^^^^^
SyntaxError: Unexpected token import
@babel/preset-env
预设来编译您的代码。
此外,该编译是由您的
--require @babel/register
Mocha 选项触发的。的工作原理是“将自身绑定到节点的 require 并自动动态编译文件”。这是
@babel/register
的基本示例:
从命令行:
$ node main.js
You will see this, because there is no syntax error!
main.js
require('@babel/register');
// This next file is compiled on the fly
require('./file1.js');
文件1.js
import path from 'path';
console.log('You will see this, because there is no syntax error!');
好的一面是,这就是 Mocha 建议您在其文档中集成 Babel 的方式。
--require
选项基本上执行上面示例的操作:在 Mocha 使用 require('@babel/register');
导入所有测试文件之前调用
require
。
希望这有帮助!再说一遍,在 JavaScript 快速发展的现代,这是一个完全可以理解的谜团。