基於create-react-app的優化和eslint配置

這是對現有的項目基於create-react-app作的優化javascript

若是項目中使用了yarn eject

  • 這種方式把配置暴露出來了,能夠參考其餘文章基於webpack作一些優化

使用@craco/craco來重寫webpack配置

  • 安裝此插件 yarn add @craco/craco -D
  • 更改package.json中的script指令
    "scripts": {- "start": "react-scripts start",+ "start": "craco start",- "build": "react-scripts build",+ "build": "craco build"- "test": "react-scripts test",+ "test": "craco test"}    
複製代碼
  • 在項目的根目錄創建 craco.config.js, 配置文件以下:

注意某些模塊須要本身安裝css

const path = require('path')const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') // 分析模板依賴大小用的,我這邊只配置了在開發時打開服務器const CompressionWebpackPlugin = require('compression-webpack-plugin') // 打包時壓縮代碼成gz,若是服務器開啓了gzip能夠大大壓縮大小const CracoLessPlugin = require('craco-less') // 配合按需加載antd 和 修改主題使用const WebpackBar = require('webpackbar') // 顯示打包進度條用的const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') // 緩存用的,第二次打包和構建會極大提高速率const resolve = (dir) => path.resolve(__dirname, dir)const env = process.env.REACT_APP_ENVconst getAnalyzerConfig = (env) => {  if (env === 'production') {return {      analyzerMode: 'disabled'}
  }
}module.exports = ({ env: webpackEnv }) => {  return {webpack: {      plugins: [new BundleAnalyzerPlugin(          Object.assign(
            {},
            {              analyzerPort: 'auto',              openAnalyzer: webpackEnv !== 'production',              generateStatsFile: false,              defaultSizes: 'gzip',              analyzerMode: 'server'},
            getAnalyzerConfig(webpackEnv)
          )
        ),new CompressionWebpackPlugin({          filename: '[path].gz[query]',          algorithm: 'gzip',          test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),          threshold: 1024,          minRatio: 0.8}),new WebpackBar({          name: webpackEnv !== 'production' ? '正在啓動' : '正在打包',          color: '#fa8c16'}),new HardSourceWebpackPlugin()
      ],      alias: {'@': resolve('src')
      },      // configure這裏能夠拿到create-react-app的全部webpack配置,某些在外面修改不了的配置,能夠在這配置  configure: (webpackConfig, { env: webpackEnv, paths }) => {// console.log(env, paths)paths.appBuild = path.join(path.dirname(paths.appBuild), `build-${env}`)
        webpackConfig.output = {
          ...webpackConfig.output,
          ...{path: paths.appBuild
          }
        }
        webpackConfig.devtool = webpackEnv !== 'production' ? 'eval-source-map' : 'none'return webpackConfig
      }
    },// 下面是antd 的按需加載用的,不用每次導入css文件babel: {      plugins: [
        [          'import',
          {libraryName: 'antd',libraryDirectory: 'es',style: true  }
        ]
      ]
    },plugins: [
      {plugin: CracoLessPlugin,options: {          lessLoaderOptions: {lessOptions: {              modifyVars: {'@primary-color': '#1890ff'  }, //主題顏色  javascriptEnabled: true}
          }
        }
      }
    ]
  }
}複製代碼

添加eslint

  1. 安裝所須要的依賴
yarn add eslint-config-prettier eslint-plugin-prettier prettier -D複製代碼
  1. 去掉package.json 裏面的eslint字段
- "eslintConfig": {-    "extends": "react-app"-  }複製代碼
  1. 項目根目錄增長.editorconfig .prettierrc .eslintrc.json .env文件
.editorconfig 文件

root = true[*]
indent_style = space
indent_size = 2charset = utf-8trim_trailing_whitespace = trueinsert_final_newline = trueend_of_line = lf

[*.md]
trim_trailing_whitespace = true.prettierrc 文件

{  "trailingComma": "none",  "tabWidth": 2,  "semi": false,  "singleQuote": true,  "jsxSingleQuote": true,  "endOfLine": "lf",  "printWidth": 120,  "bracketSpacing": true,  "arrowParens": "always",  "useTabs": false}

.eslintrc.json 文件

{  "extends": ["react-app", "prettier"],  "plugins": ["prettier"],  "rules": {"prettier/prettier": ["error", { "endOfLine": "lf" }],"@typescript-eslint/no-unused-vars": ["error"],"jsx-quotes": [1, "prefer-single"],"no-class-assign": "error","no-dupe-keys": "error","no-dupe-args": "error","no-duplicate-case": "error","no-fallthrough": "error","no-func-assign": "error",// "linebreak-style": [0, "windows"],"no-multi-spaces": "warn","no-var": "error","eqeqeq": [2, "allow-null"],"quotes": [1, "single"],"no-unreachable": "error","no-multiple-empty-lines": [2, { "max": 2 }],"camelcase": "warn","react/jsx-key": 2,"react/jsx-max-props-per-line": 0,"space-infix-ops": "error"
  }
}

.env文件

EXTEND_ESLINT=true複製代碼
  1. 增長本項目vscode的設置,根目錄下創建一個.vscode文件夾,在裏面創建一個settings.json
settings.json文件

{
    "eslint.validate": [
      "javascript",
      "javascriptreact",
      "typescript",
      "typescriptreact"
    ],
    "editor.formatOnSave": true,
    "javascript.format.enable": false,
    "typescript.format.enable": false,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    }
  }  

複製代碼
  1. 須要注意安裝和開啓vscode的ESLint 和 Prettier - Code formatter 插件
相關文章
相關標籤/搜索