Node v13/Jest/ES6 — 对没有 babel 或 esm 的模块的原生支持 [英] Node v13 / Jest / ES6 — native support for modules without babel or esm

查看:30
本文介绍了Node v13/Jest/ES6 — 对没有 babel 或 esm 的模块的原生支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在没有 esmbabel 的情况下使用 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-nodejest-environment-jsdom-sixteen 运行您的测试.
  • Make sure you don't transform away import statements by setting transform: {} 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 or jest-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆