打包到生產環境時去掉SOURCEMAP
禁用生成 Source Map 是一種權衡,可以根據項目的實際需求和優化目標來決定是否禁用。如果您對調試需求不是特別強烈,可以考慮在生產構建中禁用 Source Map 以獲取更好的性能。但如果需要保留調試能力,可以在生產構建中保留生成 Source Map
“buildProd”: “BUILD_ENV=prod GENERATE_SOURCEMAP=false react-app-rewired build”
配置webpack進行相關優化
- 代碼壓縮,去掉log日志
config.optimization.minimizer.push(new TerserPlugin({terserOptions: {compress: {drop_console: true,},output: {comments: false,},},}));
- 根據git版本生成輸出目錄
const gitVersion = child_process.execSync('git rev-parse --short HEAD').toString().trim();const prePath = `${gitVersion}`const staticPath = `prePath`// 更改輸出目錄config.output.path = path.resolve(__dirname, `build/`);// js chunk assetconfig.output.filename = `${prePath}/js/[name].[contenthash:8].js`;config.output.chunkFilename = `${prePath}/js/[name].[contenthash:8].chunk.js`;config.output.assetModuleFilename = `${prePath}/media/[name].[hash][ext]`;
- CDN加速,開發環境和生產環境分開
if (process.env.BUILD_ENV == "prod") {// 更改公共路徑config.output.publicPath = `https://didbrowser-prod.oss-cn-chengdu.aliyuncs.com/`}if (process.env.BUILD_ENV == "dev") {config.output.publicPath = `https://didbrowser-dev.oss-cn-chengdu.aliyuncs.com/`}
- 對第三方插件大模塊chunks 進行代碼分割
config.optimization = {...config.optimization,splitChunks: {cacheGroups: {echarts: {test: /[\\/]node_modules[\\/]echarts[\\/]/, // 匹配 ECharts 模塊name: 'echarts', // 生成的文件名chunks: 'all', // 對所有的 chunks 進行代碼分割}},},};
- 更改 CSS 的輸出路徑
const miniCssExtractPlugin = config.plugins.find(plugin => plugin instanceof MiniCssExtractPlugin);if (miniCssExtractPlugin) {miniCssExtractPlugin.options.filename = `${prePath}/css/[name].[contenthash:8].css`;miniCssExtractPlugin.options.chunkFilename = `${prePath}/css/[name].[contenthash:8].chunk.css`;}