【Nuxt】05 Nuxt2项目打包优化

1 打包优化

在nuxt.config.js配置

build: {
    // 开启打包分析
    analyze: true,
}

进行打包可以查看包体积:
image.png

element引入优化:

  • 在插件按需引入:

image.png

  • 打包分包 npm i babel-plugin-component -D,在我自己的项目里,打包后的elementUI资源可以降低至原先的30%
    • 配置
module.exports={
  build: {
      transpile: [/^element-ui/],
      babel: {
        plugins: [
          [
            'component',
            {
              libraryName: 'element-ui',
              styleLibraryName: 'theme-chalk'
            }
          ]
        ]
      },
    ...
  }
}

压缩

正好安装compression-webpack-plugin来对js文件进行压缩。

  • 安装: npm install compression-webpack-plugin
  • 在nuxt.config.js中:
const CompressionPlugin = require('compression-webpack-plugin');
module.exports={
  build: {
    plugins: [
      new CompressionPlugin({
        test: /\.js$|\.html$|\.css/, // 匹配文件名
        threshold: 10240, // 对超过10kb的数据进行压缩
        deleteOriginalAssets: false // 是否删除原文件
      })
    ],
  }
}

这样打包出来的大小虽然没变,但是点击.nuxt-dist-client中你会发现gz打包后,较原来的文件减少了3/4的体积。

nuxt-precompress:主要是压缩我们的js/html/css文件

配置好之后build一下,果然在.nuxt/dist/client里生成了压缩文件。

  • 安装: nuxt-precompress
  • 在nuxt.config.js中:
nuxtPrecompress: {
    enabled: true, // Enable in production
    report: false, // set true to turn one console messages during module init
    test: /\.(js|css|html|txt|xml|svg)$/, // files to compress on build
    middleware: {
      enabled: true,
      enabledStatic: true,
      encodingsPriority: ['br', 'gzip']
    },
    gzip: {
      enabled: true,
      filename: '[path].gz[query]', // middleware will look for this filename
      threshold: 10240,
      minRatio: 0.8,
      compressionOptions: { level: 9 }
    },
    brotli: {
      enabled: true,
      filename: '[path].br[query]', // middleware will look for this filename
      compressionOptions: { level: 11 },
      threshold: 10240,
      minRatio: 0.8
    }
  },

chunk分包

splitChunks: 設定 Chunks 的最大和最小 size。
在nuxt.config.js中加入:

module.exports={
  build: {
    optimization: {
      splitChunks: {
        minSize: 10000,
        maxSize: 250000
      }
    },
  }
}

公共业务模块提取

module.exports={
  build: {
    optimization: { // 拆分大文件
      splitChunks: {
        cacheGroups: {
          default: {
            name: 'chunk-commons',
            chunks: 'initial',
            minChunks: 3, // 模块被引用3次以上的才抽离
            priority: -20
          }
          ...
        }
      }
    },
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值