1.装包

  1. yarn add react-app-rewired customize-cra

2.创建目录

在项目根目录下创建一个config-overrides.js

  1. const path = require("path");
  2. const {
  3. override,//重写webpack配置
  4. addWebpackAlias//区别名
  5. } = require("customize-cra");
  6. module.exports = override(
  7. addWebpackAlias({
  8. ["@"]: path.resolve(__dirname, "src")
  9. }),
  10. );

3.修改package.json

  1. "scripts": {
  2. "start": "react-app-rewired start",
  3. "build": "react-app-rewired build",
  4. "test": "react-app-rewired test",
  5. "eject": "react-scripts eject"
  6. },

4.添加一个paths.json文件(ts版)

  1. {
  2. "compilerOptions": {
  3. "baseUrl": ".",
  4. "paths": {
  5. "@/*": ["src/*"],
  6. "@components/*": ["src/components/*"],
  7. "@pages/*": ["src/pages/*"],
  8. "@utils/*": ["src/utils/*"]
  9. }
  10. }
  11. }

5.在tsconbfig.json中怎加extends扩展文件

  1. {
  2. //第一行时增加的代码
  3. "extends": "./paths.json",
  4. "compilerOptions": {
  5. "target": "es5",
  6. "lib": [
  7. "dom",
  8. "dom.iterable",
  9. "esnext"
  10. ],
  11. "allowJs": true,
  12. "skipLibCheck": true,
  13. "esModuleInterop": true,
  14. "allowSyntheticDefaultImports": true,
  15. "strict": true,
  16. "forceConsistentCasingInFileNames": true,
  17. "module": "esnext",
  18. "moduleResolution": "node",
  19. "resolveJsonModule": true,
  20. "isolatedModules": true,
  21. "noEmit": true,
  22. "jsx": "react"
  23. },
  24. "include": [
  25. "src"
  26. ]
  27. }