Typescript/ES6的Jest预处理器
我正在尝试使用Jest测试一个Typescript类。因为我需要使用es6的Typescript/ES6的Jest预处理器,typescript,ecmascript-6,jestjs,Typescript,Ecmascript 6,Jestjs,我正在尝试使用Jest测试一个Typescript类。因为我需要使用es6的async/await,所以我需要先将typescript类编译成es6,然后使用babel编译成es5。为了实现这一点,我需要向预处理器添加什么。 我当前的预处理器如下所示: const tsc = require('typescript'); module.exports = { process: function(src, path) { if (path.endsWith('.ts')
async/await
,所以我需要先将typescript类编译成es6,然后使用babel编译成es5。为了实现这一点,我需要向预处理器添加什么。
我当前的预处理器如下所示:
const tsc = require('typescript');
module.exports = {
process: function(src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
return tsc.transpile(
src,
{
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React
},
path,
[]
);
}
return src;
}
};
我是否需要添加目标:tsc.ScriptTarget.ES6
?
当我这样做时,我在处理的代码中得到了一个意外标识符=
错误,它看起来像我的.ts
类的传输版本。我从中得到的信息是,我的预处理器正在将数据编译到es6,但我的es6没有被传输到es5。
还有没有现成的预处理器可以做到这一点 我建议使用一种更清洁的解决方案。一个为您完成工作的预处理器…如果您正在寻找自定义配置,以下可能是您的答案: 然而,以我的经验来看,这很好。只需确保您指定 ts jest的jest设置
“目标”:“ES6”
在\uu ts\u配置\uuu
中,或者只添加当前的typescript配置
您package.json
的外观如下:
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"globals": {
"__TS_CONFIG__": "tsconfig.json"
}
}
“开玩笑”:{
“scriptPreprocessor”:“/node_modules/ts jest/preprocessor.js”,
“全球”:{
“配置”:“tsconfig.json”
}
}
我目前使用的这个问题的解决方案是
const tsc = require('typescript');
const babel = require('babel-core');
const jestPreset = require('babel-preset-jest');
const es2015 = require('babel-preset-es2015');
const stage3 = require('babel-preset-stage-3');
module.exports = {
process: function (src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
var es6Code = tsc.transpile(
src,
{
target: tsc.ScriptTarget.ES6,
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React
},
path,
[]
);
return babel.transform(es6Code, {
auxiliaryCommentBefore: ' istanbul ignore next ',
presets: [jestPreset, es2015, stage3],
retainLines: true
}).code;
}
return src;
}
};
因此,我在这里所做的是将typescript编译器生成的传输代码传递给babel,然后babel将我的代码从es6转换为es5。如果你想使用Webstorm的集成,你必须在package.json中使用这个“globals”
。