在我的 tsconfig 中,我当前将模块 compilerOption 属性设置为“es6”,但是,当我运行 Jest 时,我收到以下错误:
Test suite failed to run
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){require('ts-jest').install();import { User } from './models/user;
^^^^^^
SyntaxError: Unexpected token import
at transformAndBuildScript (node_modules\jest-runtime\build\transform.js:320:12)
at process._tickCallback (internal\process\next_tick.js:103:7)
如果我将模块切换到“commonJS”,那么测试就可以正常运行。但是,我不需要这样做,因为 babel 插件“transform-es2015-modules-commonjs”应该为我将 ES 模块转换为 commonJS(或者我的理解不正确?)。
我怀疑我错误配置了一些小但重要的东西。谁能指出我在哪里遇到了麻烦?
提前致谢。
.tsconfig
{
"compilerOptions": {
"module": "es6", // Changing this to "commonJS" resolves the error.
"target": "es6",
"moduleResolution": "node",
"baseUrl": "src",
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"sourceMap": true,
"outDir": "ts-build",
"jsx": "preserve",
"experimentalDecorators": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"filesGlob": [
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules",
"dist"
]
}
.babelrc
{
"presets": [
"es2015",
"react",
"stage-0",
{"modules": false}
],
"env": {
"test": {
"plugins": [
"transform-es2015-modules-commonjs"
]
}
}
}
package.json 的 Jest 部分
"jest": {
"transform": {
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
},
"testPathDirs": [
"./src"
],
"collectCoverage": true,
"testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js"
}
注:我也关注了官方推荐 http://facebook.github.io/jest/docs/webpack.html#using-with-webpack-2用于使用 webpack 2 进行设置。