如何使用 craco 为 Jest 设置别名

Sat*_*chi 9 reactjs jestjs craco

我正在构建由 create-react-app 提供的 React 应用程序。

\n

我使用 craco 来简化配置,并为 TypeScript 和 Webpack 设置了 alise。

\n

但是当我运行测试命令时,显示以下错误。

\n
    \n
  • 错误信息
  • \n
\n
 spec/showMessage.test.tsx\n  \xe2\x97\x8f Test suite failed to run\n\n    Cannot find module '@/components/atom/TextButton' from 'src/pages/index.tsx'\n\n    Require stack:\n      src/pages/index.tsx\n      spec/showMessage.test.tsx\n\n      3 | import styled from 'styled-components';\n      4 | \n    > 5 | import { TextButton } from '@/components/atom/TextButton';\n        | ^\n\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的 craco.config.js

\n
    \n
  • craco.config.js
  • \n
\n
const path = require("path");\n\nmodule.exports = {\n  jest: {\n    configure: {\n      roots: ['<rootDir>/src', '<rootDir>/spec'],\n      testMatch: ['<rootDir>/spec/**/*.{spec,test}.{js,jsx,ts,tsx}'],\n    },\n  },\n  webpack: {\n    alias: {\n      "@": path.resolve(__dirname, "./src/"),\n      "@@": path.resolve(__dirname, "./")\n    },\n    extensions: ['.ts', '.tsx'],\n  },\n};\n\n
Run Code Online (Sandbox Code Playgroud)\n

Sat*_*chi 19

我找到了解决方案,我更新package.json如下,它解决了这个问题。

{
  "name": "xxxxx",
   :
    
  },
  "jest": {
    "moduleNameMapper": {
      "^@/(.+)": "<rootDir>/src/$1"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @FelipeCandalCampos 在这个特定的实例中,左侧是一个正则表达式,它捕获使用“@/”后剩余的字符串。右侧使用捕获组中的匹配(通过反向引用)作为确定用户尝试到达的路径的方法。 (3认同)