Node v13/Jest/ES6 — 对没有 babel 或 esm 的模块的原生支持 [英] Node v13 / Jest / ES6 — native support for modules without babel or esm
问题描述
是否可以在没有 esm
或 babel
的情况下使用 Jest 测试 ES6 模块?由于node v13
原生支持es6已经尝试过:
Is it possible to test ES6 Modules with Jest without esm
or babel
? Since node v13
supports es6 natively have tried:
//package.json
{
…
"type": "module"
…
}
//__tests__/a.js
import Foo from '../src/Foo.js';
$ npx jest
Jest encountered an unexpected token
…
Details:
/home/node/xxx/__tests__/a.js:1
import Foo from '../src/Foo.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
当 babel 添加一个转译器时,它可以工作,但是 es6 模块也可以在本地使用吗?
When babel is added a transpiler, it works, but can es6 modules be used natively as well?
推荐答案
是的,可以从 jest@25.4.0
开始.从这个版本开始,有一个对 esm 的原生支持,所以你不必再用 babel 来编译你的代码.
Yes, it is possible from jest@25.4.0
. From this version, there is a native support of esm, so you will not have to transpile your code with babel anymore.
它还没有被记录下来,但是根据这个问题你必须做 3实现这一目标的简单步骤(在撰写此答案时):
It is not documented yet, but according to this issue you have to do 3 easy steps to achieve that (At the time of writing this answer):
- 确保不会通过在 jest 配置文件中设置
transform: {}
来转换import
语句 - 运行
node@^12.16.0 ||>=13.2.0
带有--experimental-vm-modules
标志 - 使用
jest-environment-node
或jest-environment-jsdom-sixteen
运行您的测试.
- Make sure you don't transform away
import
statements by settingtransform: {}
in your jest config file - Run
node@^12.16.0 || >=13.2.0
with--experimental-vm-modules
flag - Run your test with
jest-environment-node
orjest-environment-jsdom-sixteen
.
所以你的笑话配置文件应该至少包含这个:
So your jest config file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
并且要设置 --experimental-vm-modules
标志,您必须从 package.json
运行 Jest,如下所示(我希望这会改变将来):
And to set --experimental-vm-modules
flag, you will have to run Jest from package.json
as follows (I hope this will change in the future):
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}
希望这个回答对你有帮助.
I hope, this answer was helpful to you.
这篇关于Node v13/Jest/ES6 — 对没有 babel 或 esm 的模块的原生支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!