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

oli*_*ren 8 mocha.js typescript babeljs

tldr; 我希望一次将我的JS项目转换为TS一个文件,而无需构建步骤即可运行Mocha测试。

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

我遵循了有关使用Microsoft(相对)新的babel插件进行TypeScript入门的指南@babel/preset-typescript。在基本情况下,此方法效果很好:将app.js转换为app.ts。

它没有涉及的是如何进行逐步过渡。对我来说,修复3978个打字错误(执行之后的实际计数<code>find</code> ...)有点不知所措,并且会使开发停滞两周。刚react-redux花了一个多小时,才使我的200个LOC帮助程序lib可以很好地编译来自的定义。

尽管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透明地运行它们?

Cam*_*oan 5

以下是我如何在我们的混合 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'
};
Run Code Online (Sandbox Code Playgroud)
// 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.
Run Code Online (Sandbox Code Playgroud)
// package.json
{
  "scripts": {
    "test": "mocha"
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:包括转换后的 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
    ]
}
Run Code Online (Sandbox Code Playgroud)