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"
  },
複製代碼
相關文章
相關標籤/搜索