| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- const path = require('path')
- const CompressionPlugin = require('compression-webpack-plugin')
- function resolve(dir) {
- return path.join(__dirname, dir)
- }
- module.exports = {
- // 1. 生产环境禁用 source map,极大减少打包体积并保护源码
- productionSourceMap: false,
- lintOnSave: process.env.NODE_ENV !== 'production',
- configureWebpack: config => {
- const plugins = []
- // 2. 生产环境开启 Gzip 压缩
- if (process.env.NODE_ENV === 'production') {
- plugins.push(
- new CompressionPlugin({
- filename: '[path].gz[query]',
- algorithm: 'gzip',
- test: /\.(js|css|html|svg)$/, // 匹配文件名
- threshold: 10240, // 对超过 10kb 的数据进行压缩
- minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
- deleteOriginalAssets: false // 是否删除原文件(通常建议保留)
- })
- )
- }
- return {
- plugins,
- resolve: {
- alias: {
- '@': resolve('src'),
- 'assets': resolve('src/assets'),
- 'components': resolve('src/components'),
- 'network': resolve('src/network'),
- 'views': resolve('src/views')
- }
- },
- // 3. 性能提示配置
- performance: {
- hints: 'warning',
- maxEntrypointSize: 512000,
- maxAssetSize: 512000
- }
- }
- },
- chainWebpack: config => {
- // 4. 优化 Prismjs 注入 (配合 babel-plugin-prismjs 使用)
- // 确保只加载必要的语言,防止 vendor 膨胀
- // 5. swf 支持保持不变
- config.module
- .rule('swf')
- .test(/\.swf$/)
- .use('url-loader')
- .loader('url-loader')
- .options({
- limit: 10000
- })
- // 6. 移除 prefetch/preload,减少首屏不必要的流量消耗
- config.plugins.delete('prefetch')
- config.plugins.delete('preload')
- // 7. 图片压缩 (可选,需安装 image-webpack-loader)
- // 8. 分包策略:将体积大的库单独拆出
- if (process.env.NODE_ENV === 'production') {
- config.optimization.splitChunks({
- chunks: 'all',
- cacheGroups: {
- libs: {
- name: 'chunk-libs',
- test: /[\\/]node_modules[\\/]/,
- priority: 10,
- chunks: 'initial'
- },
- elementUI: {
- name: 'chunk-elementUI',
- priority: 20, // 权重需大于 libs
- test: /[\\/]node_modules[\\/]_?element-ui(.*)/
- },
- commons: {
- name: 'chunk-commons',
- test: resolve('src/components'),
- minChunks: 3,
- priority: 5,
- reuseExistingChunk: true
- }
- }
- })
- }
- },
- devServer: {
- port: 4040,
- disableHostCheck: true,
- overlay: {
- warnings: false,
- errors: true
- }
- },
- pluginOptions: {
- 'style-resources-loader': {
- preProcessor: 'scss',
- patterns: [
- path.resolve(__dirname, './src/assets/css/variable.scss')
- ]
- }
- },
- publicPath: '/'
- }
|