【问题标题】:How to use path alias in a react project with Typescript + Jest如何在带有 Typescript + Jest 的反应项目中使用路径别名
【发布时间】:2018-12-07 10:07:18
【问题描述】:

我一直在我的 react 项目(打字稿)中使用 jest 进行单元测试。现在我在 webpack 和 tsconfig 中启用了路径别名。为了在玩笑中使用路径别名,我遵循了这个tutorial。但是当我运行测试时出现此错误:

这是我启用路径别名的 webpack 配置:

alias: {
  'ui': path.resolve(__dirname, 'src/framework/components/ui')
}

这是我启用路径别名 (package.json) 的玩笑配置

"moduleNameMapper": {
    "ui": "<rootDir>/src/framework/components/ui/"
}

我也尝试过教程中的这个版本:

"moduleNameMapper": {
   "^ui/(.*)$1": "<rootDir>/src/framework/components/ui/$1"
}

最后是我的 tsconfig.json 配置:

"baseUrl": "src",
"paths": {
  "ui": ["framework/components/ui"]      
}

当我运行测试时,jest 实际上会解析路径别名。但它无法拾取默认公开的组件。例如这一行:

import Button from './FormComponents/Button';

失败,因为“按钮”是从其模块默认导出的。

我希望我的问题是有道理的。提前感谢您的帮助。

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    使用ts-jesthttps://huafu.github.io/ts-jest/user/config/#jest-config-with-helper

    // jest.config.js
    const { pathsToModuleNameMapper } = require('ts-jest/utils');
    // In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
    // which contains the path mapping (ie the `compilerOptions.paths` option):
    const { compilerOptions } = require('./tsconfig');
    
    module.exports = {
      // [...]
      moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */ )
    };
    

    【讨论】:

    • 这行得通!我需要前缀,但完全可以,非常感谢!
    【解决方案2】:

    试试

    "moduleNameMapper": {
       "^ui/(.*)": "<rootDir>/src/framework/components/ui/$1"
    }
    

    正则表达式中不应包含 $1,因为 $1 在替换字符串中用于插入捕获的文本。

    例如在您的示例中,“Button”将被 (.*) 捕获,然后用于替换替换字符串中的 $1。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2014-08-23
      • 2019-08-01
      • 2021-12-20
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2019-06-30
      相关资源
      最近更新 更多