webpack的打包优化方案

1.js的压缩。可以用插件uglifyjs-webpack-plugin
该模块需要的环境: node 6.9.0 webpack 4.0.0 版本以上

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
new UglifyJsPlugin({
  uglifyOptions: {
    compress: {
      drop_debugger: true, // console
      drop_console: true,
       pure_funcs: ['console.log'] // 移除console
     }
   },
   sourceMap: false,
   parallel: true
})
  1. compression-webpack-plugin 开启gzip
const CompressionWebpackPlugin = require('compression-webpack-plugin')
      config.plugins.push(
        new CompressionWebpackPlugin({
          algorithm: 'gzip',
          test: new RegExp(`\\.(${productionGzipExtensions.join('|')})$`),
          threshold: 10240
        })
      )

3.hard-source-webpack-plugin为模块提供中间缓存步骤。为了查看结果,您需要使用此插件运行webpack两次:第一次构建将花费正常的时间。第二次构建将显着加快(大概提升90%的构建速度)。

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
        new HardSourceWebpackPlugin({
          cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
          recordsPath: 'node_modules/.cache/hard-source/[confighash]/records.json',
          configHash: function (webpackConfig) {
            // node-object-hash on npm can be used to build this.
            return require('node-object-hash')({ sort: false }).hash(webpackConfig)
          },
          environmentHash: {
            root: process.cwd(),
            directories: [],
            files: ['package-lock.json', 'yarn.lock']
          }
        })

4.webpack-parallel-uglify-plugin 多线程压缩

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
new ParallelUglifyPlugin({ // 多进程压缩
          cacheDir: '.cache/',
          uglifyJS: {
            output: {
              comments: false,
              beautify: false
            },
            compress: {
              warnings: false,
              drop_console: true,
              collapse_vars: true,
              reduce_vars: true
            }
          }
        })

5.progress-bar-webpack-plugin 编译进度条

const ProgressBarPlugin = require('progress-bar-webpack-plugin')
new ProgressBarPlugin({ 
  format: ' build [:bar]' + chalk.green.bold(':percent') + ' (:elapsed seconds)',
  clear: false
})

6.DllReferencePlugin,这个插件是在webpack.config.js中使用的,该插件的作用是把刚刚在webpack.dll.config.js中打包生成的dll文件引用到需要的预编译的依赖上来。在我们编辑过一次插件后,在后续只想编译,业务代码,这样就可以用这个代码,把业务代码和插件代码分开编译。特别能提高我们打包的速度,特别在我们项目越来越大后提现了很强大的功能。
1).在项目下新建一个webpack.dll.config.js文件

const path = require('path')
const DllPlugin = require('webpack/lib/DllPlugin')
const packageFile = require('./package')
let dependcyArr = Object.keys(packageFile.dependencies)
let entryObj = {
  base: []
}
dependcyArr.map((item) => {
  if (/element-ui/g.test(item)) {
    entryObj.elementUI = [item]
  } else if (/echarts/g.test(item)) {
    entryObj.echarts = [item]
  } else {
    entryObj.base.push(item)
  }
})
module.exports = {
  // 入口文件
  entry: entryObj, // 项目中用到依赖库文件
  // 输出文件
  output: {
    // 文件名称
    filename: '[name].dll.js',
    // 将输出的文件放到dist目录下
    path: path.resolve(__dirname, 'dist/dll/js'),
    /*
     存放相关的dll文件的全局变量名称,比如对于jquery来说的话就是 _dll_jquery, 在前面加 _dll
     是为了防止全局变量冲突。
    */
    library: '_dll_[name]'
  },
  plugins: [
    // 使用插件 DllPlugin
    new DllPlugin({
      /*
       该插件的name属性值需要和 output.library保存一致,该字段值,也就是输出的 manifest.json文件中name字段的值。
       比如在jquery.manifest文件中有 name: '_dll_jquery'
      */
      name: '_dll_[name]',
      /* 生成manifest文件输出的位置和文件名称 */
      path: path.resolve(__dirname, 'dist/dll/manifest', '[name].manifest.json')
    })
  ]
}

2).在vue.config.js下修改配置项

// 引入 DllReferencePlugin
const DllReferencePlugin = require('webpack/lib/DllReferencePlugin')
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')
const webpackDLLFile = require('./webpack.dll.config.js')
let webpackDLLArr = Object.keys(webpackDLLFile.entry)
let  currentDll = webpackDLLArr
      currentDll.map((item) => {
        config.plugins.push(
          new DllReferencePlugin({
            // 第三方库 映射到json文件上去
            manifest: require(`./dist/dll/manifest/${item}.manifest.json`)
          })
        )
        config.plugins.push(
          new AddAssetHtmlWebpackPlugin({
            filepath: path.resolve(__dirname, `dist/dll/js/${item}.dll.js`)
          })
        )
      })
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容