运行 Mocha 测试时混合打字稿和 javascript 模块

Mixing typescript and javascript modules when running Mocha tests

tldr;我想一次将我的 JS 项目转换为 TS 一个文件,同时能够 运行 Mocha 测试而无需构建步骤。

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

我关注了a guide on getting started with TypeScript using the (relatively) new babel plugin from Microsoft@babel/preset-typescript。这对于基本情况非​​常有效:将 app.js 转换为 app.ts.

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

虽然 git mv app.{j,t}s 工作正常,但对任何其他文件执行此操作是一场灾难。现有的 Mocha 测试由于无法找到正确的文件而迅速崩溃,即使在注册 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 科学怪人代码库中实现这一点。 mocha 只是在执行我们的测试之前转换代码。这使得这一切都在一个步骤中发生,而不是两个单独的步骤。这是我下面的配置。您可以通过将这些添加为 cli 标志来替换 mocha opts。

// .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
    ]
}