[英]Jest and ESM throwing errors with import fs
I am converting a node package into pure ESM.我正在将节点 package 转换为纯 ESM。 I have done the import changes to my files, added
"type":"module"
to package.json
and also used "exports":"./lib/index.js"
我已经对我的文件进行了导入更改,将
"type":"module"
添加到package.json
并且还使用了"exports":"./lib/index.js"
When I run the test, I get the this common error:当我运行测试时,我得到了这个常见的错误:
/x/__tests__/values.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fs from 'fs'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I've looked only, through many examples and Q&A, but almost all of them refers to changes with ts-node
or babel
.我只看过许多示例和问答,但几乎所有这些都指的是
ts-node
或babel
的更改。 My package is quite simple, it does not use babel
and it's plain javascript.我的 package 非常简单,它不使用
babel
,它是普通的 javascript。
I am getting a bit stuck here, because I am nearly sure it's not a bug, but also I can't fix it.我在这里有点卡住了,因为我几乎可以肯定这不是一个错误,但我也无法修复它。
I do not have any transform
or transformIgnorePatterns
.我没有任何
transform
或transformIgnorePatterns
。 The test import section is测试导入部分是
import fs from 'fs'
import { values } from "../lib/index.js"
const expectedData = JSON.parse(fs.readFileSync(__dirname + "/testfiles/values.output.json"))
Jest is version 29.0.1
Jest 是版本
29.0.1
Node is version 16.17.0
节点是版本
16.17.0
Jest does not understand ESM syntax out of the box. Jest 不理解开箱即用的 ESM 语法。
Jest ships with experimental support for ECMAScript Modules (ESM).
Jest 附带了对 ECMAScript 模块 (ESM) 的实验性支持。
It is experimental and has many bugs.它是实验性的,有很多错误。
You need to transpile your ESM syntax to CJS when running tests.运行测试时,您需要将 ESM 语法转换为 CJS。
Babel is one option通天塔是一种选择
.babelrc
file with the following content.babelrc
文件{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
npm i -D @babel/plugin-transform-modules-commonjs
And that's it, now you can use ESM syntax in your tests.就是这样,现在您可以在测试中使用 ESM 语法。
If you want something else you can check the official docs如果您想要其他内容,可以查看官方文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.