[英]Jest preprocessor for Typescript/ES6
我正在嘗試使用Jest測試Typescript類。 由於我需要使用es6的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;
}
};
我是否需要添加target: tsc.ScriptTarget.ES6
? 當我這樣做時,在處理后的代碼中unexpected identifier =
錯誤,看起來像我的.ts
類的轉譯版本。 我從中收集到的是我的預處理器正在將數據編譯到es6,但是我的es6沒有被編譯到es5。 還有任何現成的預處理器可以做到這一點嗎?
我建議使用https://www.npmjs.com/package/ts-jest ,這是一種更干凈的解決方案。 可以為您完成工作的預處理器...
如果您正在尋找自定義配置,這可能是您的答案: https : //stackoverflow.com/a/40070453/4909970
但是,以我的經驗, ts-jest可以正常工作。 只需確保在__TS_CONFIG__
為ts-jest "target": "ES6"
指定了jest設置,或僅添加當前的打字稿配置。
您的package.json
將如下所示:
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"globals": {
"__TS_CONFIG__": "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,后者將我的代碼從es6轉換為es5。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.