React官方文档推荐使用CRA ( create-react-app )来创建项目,其中会隐藏起有关webpack的配置,可以通过npm run eject修改相关配置,但是这个操作时不可逆的❗️也就是说一旦执行了此操作,那么webpack相关的处理都需要自行进行处理,比如说配置、构建等。对于小白来说,还是不要轻易尝试的好。
如果想要配置路径别名或者less等操作时,可以通过craco进行配置。
首先安装craco
npm i @craco/craco
配置less
npm i croco-less -D
const CracoLessPlugin = require('craco-less')
module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { javascriptEnabled: true } } } } ], }
|
移动端自适应 postcss-pxtorem
npm i postcss-pxtorem -D
import ‘lib-flexible’;
const postcssPx2Rem = require('postcss-pxtorem') module.exports = { style: { postcss: { mode: 'extends', loaderOptions: () => { return { postcssOptions: { ident: 'postcss', config: false, plugins: [ postcssPx2Rem({ rootValue: 37.5, propList: ['*'], exclude: /node_modules/i }) ] }, sourceMap: false } } } }, }
|
代理
module.exports = { devServer: { port: 8888, hot: true, client: { overlay: false }, proxy: { '/': { target: process.env.REACT_APP_URL, changeOrigin: true, pathRewrite: { '^/': '' } } } }
}
|
路径别名和打包大小分析
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') module.exports = { webpack: { alias: { '@': path.resolve(__dirname, 'src') },
plugins: [ ], } }
|
拆包和打包路径
module.exports = { webpack: { configure: webpackConfig => { if (isProd) { webpackConfig.devtool = false webpackConfig.optimization = { splitChunks: { chunks: 'async', minSize: 40000, maxAsyncRequests: 10, maxInitialRequests: 10, automaticNameDelimiter: '~', name: false, cacheGroups: { antd: { name: 'chunk-antd', chunks: 'all', test: /[\\/]node_modules[\\/](@ant-design|antd-mobile)[\\/]/, priority: -7 }, common: { name: 'chunk-common', chunks: 'all', test: /[\\/]node_modules[\\/](react|react-dom|react-router|react-redux|react-router-dom|redux-persist|react-fastclick)[\\/]/, priority: -9 }, vendor: { name: 'chunk-vendor', chunks: 'all', test: /[\\/]node_modules[\\/](axios|lodash|core-js|react-copy-to-clipboard|crypto-js|web-vitals)[\\/]/, priority: -10 } } } } webpackConfig.output = { ...webpackConfig.output, publicPath: './' } } return webpackConfig } }, }
|
移除开发日志console.log
module.exports = { babel: { plugins: [ [ 'babel-plugin-transform-remove-console', { exclude: isProd ? ['error', 'warn'] : ['error', 'warn', 'log'] } ] ] }, }
|
修改项目运行命令
package.json
{ "scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "eject": "react-scripts eject" }, }
|
加载开发、测试、生产不同环境的环境变量
使用dotenv-cli
npm i dotenv-cli -D
{ "scripts": { "prod": "dotenv -e .env.production craco start", "build:dev": "dotenv -e .env.development craco build", "build:test": "dotenv -e .env.test craco build", "build:prod": "dotenv -e .env.production craco build", "lint": "eslint -c .eslintrc.js src --ext .ts,.tsx,.js,.jsx --fix", "clean": "rimraf node_modules" }, }
|