无法在使用Jest的模块外使用import语句 [英] Cannot use import statement outside a module using jest
问题描述
我正在使用jest在lib上运行一些测试,并且出现了无法在模块外部使用import语句"错误.在我升级了一个现在可以导出到es6的库之后,在升级之前测试就可以了.
I'm using jest to run some tests on a lib and I've been getting the error "Cannot use import statement outside a module" after I upgraded a lib that now exports to es6, before the upgrade the tests worked just fine.
错误的屏幕截图:
我正在使用的jest.config.js文件:
The jest.config.js file that I'm using:
module.exports = {
roots: ['<rootDir>/src/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
tsconfig.json文件:
The tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es6", "dom"],
"types": ["jest"],
"sourceMap": true,
"jsx": "react",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"strict": true,
"emitDecoratorMetadata": true,
"importHelpers": true,
"noEmitHelpers": true,
"noFallthroughCasesInSwitch": true,
"strictFunctionTypes": false,
"pretty": true,
"removeComments": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true,
"baseUrl": "./"
}
}
最后是babel.config.js文件:
And lastly, the babel.config.js file:
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
ie: '11',
},
},
],
'@babel/typescript',
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-object-assign',
'@babel/plugin-transform-runtime',
],
env: {
development: {},
production: {
plugins: ['transform-dev-warning'],
ignore: ['**/test/'],
},
test: {
sourceMaps: 'both',
},
},
};
我已经尝试了几乎所有可以在网上找到的解决方案,但似乎无济于事.如果有人可以帮助我,那就太好了,谢谢!!
I've tried pretty much every solution that I could find online but nothing seems to work. If anybody could help me that would be great, thanks in advance!
推荐答案
问题
这是非常常见的问题,使用(import
)一种导致问题的esm
js样式.在这种情况下,程序包为sip.js
.
Problem
This is very common issue by using (import
) an esm
js style that causes the issue. In this case the package is sip.js
.
该解决方案也很常见,我们只需配置jest
即可使用魔术选项transformIgnorePatterns
转换该软件包.另外,还要告诉tsc
也编译该esm
软件包.
The solution is also very common as well which we just simply configure jest
to transform that package by using magic option transformIgnorePatterns
. Plus, also tell tsc
to compile that esm
package too.
简而言之,这是您要做的事情:
In short, here are the thing you would do:
jest.config.js
module.exports = {
// ...
transform: {
'^.+\\(t|j)sx?$': 'ts-jest', // transpile both `ts` + `js` files
},
transformIgnorePatterns: [`/node_modules/(?!(sip\.js))`] // Keep `sip.js` to get transpiled as well
};
这篇关于无法在使用Jest的模块外使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!