节点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
语句 - 使用
--experimental-vm-modules
标志运行node@^12.16.0 || >=13.2.0
- 使用
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.
这篇关于节点v13/Jest/ES6 —对没有babel或esm的模块的本机支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!