vue.config.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. const path = require('path')
  2. const CompressionPlugin = require('compression-webpack-plugin')
  3. function resolve(dir) {
  4. return path.join(__dirname, dir)
  5. }
  6. module.exports = {
  7. // 1. 生产环境禁用 source map,极大减少打包体积并保护源码
  8. productionSourceMap: false,
  9. lintOnSave: process.env.NODE_ENV !== 'production',
  10. configureWebpack: config => {
  11. const plugins = []
  12. // 2. 生产环境开启 Gzip 压缩
  13. if (process.env.NODE_ENV === 'production') {
  14. plugins.push(
  15. new CompressionPlugin({
  16. filename: '[path].gz[query]',
  17. algorithm: 'gzip',
  18. test: /\.(js|css|html|svg)$/, // 匹配文件名
  19. threshold: 10240, // 对超过 10kb 的数据进行压缩
  20. minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
  21. deleteOriginalAssets: false // 是否删除原文件(通常建议保留)
  22. })
  23. )
  24. }
  25. return {
  26. plugins,
  27. resolve: {
  28. alias: {
  29. '@': resolve('src'),
  30. 'assets': resolve('src/assets'),
  31. 'components': resolve('src/components'),
  32. 'network': resolve('src/network'),
  33. 'views': resolve('src/views')
  34. }
  35. },
  36. // 3. 性能提示配置
  37. performance: {
  38. hints: 'warning',
  39. maxEntrypointSize: 512000,
  40. maxAssetSize: 512000
  41. }
  42. }
  43. },
  44. chainWebpack: config => {
  45. // 4. 优化 Prismjs 注入 (配合 babel-plugin-prismjs 使用)
  46. // 确保只加载必要的语言,防止 vendor 膨胀
  47. // 5. swf 支持保持不变
  48. config.module
  49. .rule('swf')
  50. .test(/\.swf$/)
  51. .use('url-loader')
  52. .loader('url-loader')
  53. .options({
  54. limit: 10000
  55. })
  56. // 6. 移除 prefetch/preload,减少首屏不必要的流量消耗
  57. config.plugins.delete('prefetch')
  58. config.plugins.delete('preload')
  59. // 7. 图片压缩 (可选,需安装 image-webpack-loader)
  60. // 8. 分包策略:将体积大的库单独拆出
  61. if (process.env.NODE_ENV === 'production') {
  62. config.optimization.splitChunks({
  63. chunks: 'all',
  64. cacheGroups: {
  65. libs: {
  66. name: 'chunk-libs',
  67. test: /[\\/]node_modules[\\/]/,
  68. priority: 10,
  69. chunks: 'initial'
  70. },
  71. elementUI: {
  72. name: 'chunk-elementUI',
  73. priority: 20, // 权重需大于 libs
  74. test: /[\\/]node_modules[\\/]_?element-ui(.*)/
  75. },
  76. commons: {
  77. name: 'chunk-commons',
  78. test: resolve('src/components'),
  79. minChunks: 3,
  80. priority: 5,
  81. reuseExistingChunk: true
  82. }
  83. }
  84. })
  85. }
  86. },
  87. devServer: {
  88. port: 4040,
  89. disableHostCheck: true,
  90. overlay: {
  91. warnings: false,
  92. errors: true
  93. }
  94. },
  95. pluginOptions: {
  96. 'style-resources-loader': {
  97. preProcessor: 'scss',
  98. patterns: [
  99. path.resolve(__dirname, './src/assets/css/variable.scss')
  100. ]
  101. }
  102. },
  103. publicPath: '/'
  104. }