模块别名无法解决(CRA和custom-cra)

时间:2019-06-27 17:24:05

标签: reactjs create-react-app

我使用CRA创建了一个React应用,并添加了exports.findNames = async () => { const names= await Student.find(); console.log('Names:', names); return names; }; node ./demo findNames 我在react-app-rewired

中映射了一些模块
TypeScript

,并在tsconfig.json

中将它们定义为别名模块。
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@constants/*": ["constants/*"],
      "@components/*": ["components/*"],
      "@grid/*": ["components/Grid/*"],
      "@grid-share/*": ["components/Grid/Share/*"],
      "@utils/*": ["util/*"],
      "@services/*": ["Services/*"]
    }
  },
  "extends": "../tsconfig.json"
}

对于config-overrides.js来说一切正常,但是对于const path = require('path'); const { override, addBabelPlugins } = require('customize-cra'); module.exports = override( ...addBabelPlugins( [ 'module-resolver', { root: ["./src"], alias: { "@constants": "./src/constants", "@components": "./src/components", "@grid": "./src/components/grid", "@utils": "./src/util", "@services": "./src/Services", "@grid-share": "./src/components/Grid/Share" } } ], ), ); 来说,它无法解析已定义的模块。为yarn start解析别名模块应该怎么做?

1 个答案:

答案 0 :(得分:0)

Okey,我找到了答案。我们需要在package.json中定义相同的模块别名

 "jest": {
    "moduleNameMapper": {
      "@constants/(.*)": "<rootDir>/src/constants/$1",
      "@utils/(.*)": "<rootDir>/src/util/$1",
      "@grid-share/(.*)": "<rootDir>/src/components/Grid/Share/$1",
      "@grid/(.*)": "<rootDir>/src/components/Grid/$1"
    }
  },