gpt4 book ai didi

reactjs - 如何使用 craco 为 Jest 设置别名

转载 作者:行者123 更新时间:2023-12-04 16:25:17 25 4
gpt4 key购买 nike

我正在构建由 create-react-app 提供的 React 应用程序。
我使用 craco 来简化配置,并为 TypeScript 和 Webpack 设置了 alise。
但是当我运行测试命令时,显示以下错误。

  • 错误信息
  •  spec/showMessage.test.tsx
    ● Test suite failed to run

    Cannot find module '@/components/atom/TextButton' from 'src/pages/index.tsx'

    Require stack:
    src/pages/index.tsx
    spec/showMessage.test.tsx

    3 | import styled from 'styled-components';
    4 |
    > 5 | import { TextButton } from '@/components/atom/TextButton';
    | ^

    这是我的 craco.config.js
  • craco.config.js
  • const path = require("path");

    module.exports = {
    jest: {
    configure: {
    roots: ['<rootDir>/src', '<rootDir>/spec'],
    testMatch: ['<rootDir>/spec/**/*.{spec,test}.{js,jsx,ts,tsx}'],
    },
    },
    webpack: {
    alias: {
    "@": path.resolve(__dirname, "./src/"),
    "@@": path.resolve(__dirname, "./")
    },
    extensions: ['.ts', '.tsx'],
    },
    };

    最佳答案

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

    {
    "name": "xxxxx",
    :

    },
    "jest": {
    "moduleNameMapper": {
    "^@/(.+)": "<rootDir>/src/$1"
    }
    }
    }

    关于reactjs - 如何使用 craco 为 Jest 设置别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65767551/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com