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

查看:241
本文介绍了节点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语句
  • 使用--experimental-vm-modules标志运行node@^12.16.0 || >=13.2.0
  • 使用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.

这篇关于节点v13/Jest/ES6 —对没有babel或esm的模块的本机支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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