打包到生产环境时去掉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`;}