我有一个包含多个模块的项目(使用 Lerna ),我想使用 Jest 来运行测试。但是,当我测试使用共享模块(通过 Lerna 的 npm 链接模块)的代码时,似乎没有正确应用 Babel,并且出现以下错误:
SyntaxError: Unexpected token import
我的项目结构是这样的:
- my-project
|- shared
|- native
|- web
web
和 native
需要 shared
模块。当我进入 shared
目录并在 Jest 中运行本地测试时,一切正常。如果我在 web
目录中运行 Jest 测试,只要我包含来自 shared
的内容,就会出现上述错误。
这是一个导致错误的 super 简单的测试:
import { util } from 'shared';
it('returns false if not prod', () => {
expect(util.isProd()).toBe(false);
});
我的 .babelrc
看起来像这样:
{
"presets": [
"env",
"flow",
"react"
],
"plugins": [
"flow-react-proptypes",
"transform-object-rest-spread",
"transform-class-properties"
]
}
我尝试了所有我能找到的东西,包括:
- 不同的 Babel 配置,包括带有
es2015
预设和为测试环境启用modules
的配置 - 为 babel-jest 手动设置
transform
选项 - 如前所述,Jest 可以在
shared
模块中执行,因此 Jest 和babel-jest
也安装在那里。
最佳答案
我必须在 web
模块的 package.json
中更改 Jest 的 transformIgnorePatterns
配置选项。
{
"jest": {
"transformIgnorePatterns": [
"<rootDir>/node_modules/(?!shared|another)"
]
},
}
关于javascript - Jest 无法从 npm 链接模块转换导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413678/