This is an optimization of an existing project based on create-React-app
If yarn Eject is used in the project
- This way the configuration is exposed, see other articles for some optimizations based on WebPack
Use @craco/craco to rewrite the WebPack configuration
- Install this plug-in
yarn add @craco/craco -D
- Change the script directive in package.json
"scripts": {
- "start": "react-scripts start",
+ "start": "craco start",
- "build": "react-scripts build",
+ "build": "craco build"
- "test": "react-scripts test",
+ "test": "craco test"
}
Copy the code
- In the root directory of the project
craco.config.js
The configuration file is as follows:
Note that some modules need to be installed yourself
const path = require('path')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') // To analyze the size of template dependencies, I only configured to open the server during development
const CompressionWebpackPlugin = require('compression-webpack-plugin') If the server has gzip enabled, the size can be greatly reduced
const CracoLessPlugin = require('craco-less') // Work with antD on demand and modify themes
const WebpackBar = require('webpackbar') // Display the progress bar
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') // For caching, the second packaging and build will greatly increase the speed
const resolve = (dir) = > path.resolve(__dirname, dir)
const env = process.env.REACT_APP_ENV
const 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' ? 'Starting' : 'Packing'.color: '#fa8c16'
}),
new HardSourceWebpackPlugin()
],
alias: {
The '@': resolve('src')},// configure configures all webpack configurations for create-react-app
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
}
},
// The following is antD on demand for loading, do not import CSS file every time
babel: {
plugins: [['import',
{
libraryName: 'antd'.libraryDirectory: 'es'.style: true}}]].plugins: [{plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: {
'@primary-color': '#1890ff'
}, // Theme color
javascriptEnabled: true}}}}]}}Copy the code
Add eslint
- Dependencies required by the installation
yarn add eslint-config-prettier eslint-plugin-prettier prettier -D
Copy the code
- Remove esLint fields from package.json
- "eslintConfig": {
- "extends": "react-app"
-}
Copy the code
- The. Editorconfig.prettierrc.eslintrc.json. env file was added to the project root directory
. Editorconfig file root =true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
[*.md]
trim_trailing_whitespace = true. {prettierrc file"trailingComma": "none"."tabWidth": 2."semi": false."singleQuote": true."jsxSingleQuote": true."endOfLine": "lf"."printWidth": 120."bracketSpacing": true."arrowParens": "always"."useTabs": false}.eslintrc.json file {"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 file EXTEND_ESLINT=true
Copy the code
- Add vscode Settings for this project, create a. Vscode folder in the root directory, and create settings.json in it
Settings. json file {"eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ], "editor.formatOnSave": true, "javascript.format.enable": false, "typescript.format.enable": false, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }Copy the code
- Install and enable ESLint and prettier-code formatter in vscode
====2020-12-31 update, add hot update plugin ====
Pay attention to thiscraco-fast-refresh
The plugin is only available in create-React-app V3; v4 has built-in support
+ const { whenDev } = require('@craco/craco')
+ const fastRefreshCracoPlugin = require('craco-fast-refresh')Add the following configuration to the plugins array in craco.config.js:+ ...whenDev(() => [
+ {
+ plugin: fastRefreshCracoPlugin
+}
+])
Copy the code