React小册 - CRA配置

配置 cra

当咱们使用 cra 脚手架搭建咱们的项目时若是须要配置 webpacknode

又不想运行 eject 命令 由于该命令是不可逆的 会暴露出全部的 webpack 配置react

这时该怎么办呢webpack

Step1

  • 安装 customize-cra react-app-rewiredgit

  • yarn add customize-cra react-app-rewired -Dgithub

Step2

根目录下新建config-overrides.js 内容以下 以配置路径别名为例子web

更多功能可参考json

const { override, addWebpackAlias } = require('customize-cra');
const path = require('path');

module.exports = override(
  // add an alias for "ag-grid-react" imports
  addWebpackAlias({
    '@': path.resolve(__dirname, './src'),
    '@store': '@/store',
    '@components': '@/components',
    '@containers': '@/containers',
    '@hooks': '@/hooks',
    '@router': '@/router',
    '@type': '@/type',
    '@utils': '@/utils',
    '@styles': '@/styles',
    '@assets': '@/assets',
  })
);
复制代码

Step3

配置tsconfig.jsonmarkdown

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@store/*": ["./src/store/*"],
      "@components/*": ["./src/components/*"],
      "@router/*": ["./src/router/*"],
      "@hooks/*": ["./src/hooks/*"],
      "@containers/*": ["./src/containers/*"],
      "@type/*": ["./src/type/*"],
      "@utils/*": ["./src/utils/*"],
      "@styles/*": ["./src/styles/*"],
      "@assets/*": ["./src/assets/*"],
      "@mock/*": ["./src/mock/*"]
    }
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}
复制代码

可是每次程序运行时 tsconfig.json 都会被从新生成 咱们配置的 paths 会消失app

能够用extends字段 配置以下dom

新建 path.json 里面放入咱们的路径配置

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@store/*": ["./src/store/*"],
      "@components/*": ["./src/components/*"],
      "@router/*": ["./src/router/*"],
      "@hooks/*": ["./src/hooks/*"],
      "@containers/*": ["./src/containers/*"],
      "@type/*": ["./src/type/*"],
      "@utils/*": ["./src/utils/*"],
      "@styles/*": ["./src/styles/*"],
      "@assets/*": ["./src/assets/*"],
      "@mock/*": ["./src/mock/*"]
    }
  }
}
复制代码

而后修改 tsconfig.json

{
  "extends": "./path.json",
  "compilerOptions": {......}
}
复制代码

Step4

package.json中 scripts 字段下的全部 react-scripts 命令改为 react-app-rewired 以下

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
复制代码
相关文章
相关标签/搜索