运行摩卡测试时混合打字稿和 JavaScript 模块



TLDR;我想一次将我的 JS 项目转换为一个文件的 TS,同时能够在没有构建步骤的情况下运行 Mocha 测试。

我在当前的 JavaScript 代码中使用了很多 Babel 转换(类 props、jsx、...),Mocha 在运行时通过注册 babel 加载器(基本上是mocha --require @babel/register个)来处理这些转换。这意味着运行单个测试速度很快,并且不需要整个项目的构建步骤。

我遵循了使用(相对)新的 babel 插件开始使用 TypeScript 的指南Microsoft:@babel/preset-typescript。这适用于基本情况:将应用程序.js转换为应用程序。

它没有涵盖的是如何进行逐步过渡。对我来说,修复 3978 个打字稿错误(执行<code>find</code> ...后的实际计数)有点压倒性,并且会使开发停滞两周。仅仅让我的 200 个 LOC 助手库就可以很好地编译react-redux的定义,这需要一个多小时。

虽然做git mv app.{j,t}s工作正常,但对任何其他文件做都是一场灾难。现有的摩卡测试很快就崩溃了,因为找不到正确的文件,即使在注册 Babel 并添加合适的扩展名时也是如此:

mocha --extension js,jsx,ts,tsx --require @babel/register

通常,如果做git mv Logger.{j,t}s我会得到Error: Cannot find module './lib/logging/Logger'.

有没有办法让 Mocha 的模块加载器识别打字稿文件并通过 Babel 透明地运行它们?

以下是我如何在我们的混合JavaScript/Typescript Frankenstein代码库中工作。 摩卡只是在执行我们的测试之前转译代码。这使得所有事情都在一个步骤中发生,而不是两个单独的步骤。这是我下面的配置。您可以将摩卡选项替换为仅将这些添加为 cli 标志。

// .mocharc.js
module.exports = {
diff: true,
extension: ['ts', 'tsx', 'js'], // include extensions
opts: './mocha.opts', // point to you mocha options file. the rest is whatever.
package: './package.json',
reporter: 'spec',
slow: 75,
timeout: 2000,
ui: 'bdd'
};
// mocha.opts
--require ts-node/register/transpile-only // This will transpile your code first without type checking it. We have type checking as a separate step.
// ...rest of your options.
// package.json
{
"scripts": {
"test": "mocha"
}
}

更新:包括转换后的 React 项目的相关 tsconfig 选项:

{
"compilerOptions": {
"noEmit": true, // This is set to true because we are only using tsc as a typechecker - not as a compiler.
"module": "commonjs",
"moduleResolution": "node",
"lib": ["dom", "es2015", "es2017"],
"jsx": "react", // uses typescript to transpile jsx to js
"target": "es5", // specify ECMAScript target version
"allowJs": true, // allows a partial TypeScript and JavaScript codebase
"checkJs": true, // checks types in .js files (https://github.com/microsoft/TypeScript/wiki/Type-Checking-JavaScript-Files)
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"esModuleInterop": true,
},
"include": [
"./src/**/*.ts",
"./src/**/*.tsx",
"./src/pages/editor/variations/**/*" // type-checks all js files as well not just .ts extension
]
}

最新更新