webpack dllPlugin使用(基于vue-cli webpack模板)

由于本例单入口时打包的文件体积过大,将其分成多入口。

主要涉及到的几个文件为:

/index.html,

/webpack.dll.config.js,

/build/webpack.base.conf.js,

/build/webpack.dev.conf.js,

/build/webpack.prod.conf.js

运行配置的dll命令如下:

webpack --config webpack.dll.config.js
  1. 新建文件webpack.dll.config.js,可以放置在任意位置,只要将路径理清即可。本例以根目录示例:
  2. const fs = require('fs')
    const path
    = require('path') const webpack = require('webpack') let vendors = [ [ 'echarts', 'echarts-wordcloud', 'element-ui' ],[ 'vue/dist/vue.esm.js', 'vue-echarts', 'vue-js-modal', 'vue-router', 'vue-waterfall', 'vuex' ] ] module.exports = { entry: {
    // 多入口,单入口情况,只需写一个,key值自定义,value值为数组 vendor0: vendors[
    0], vendor1: vendors[1] }, output: { path: path.join(__dirname, "static/dll"), filename: "[name].[chunkhash].dll.js", library: "[name]_[chunkhash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dllManifest", "[name]-manifest.json"), name: "[name]_[chunkhash]", context: __dirname }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] }

    在/build/webpack.base.conf.js中增加:

  3.   plugins: [ 
       // 这是一个数组,单入口时只需填写一个对应的webpack.DllReferencePlugin实例
    // webpack.DllReferencePlugin可以帮助webpack得知哪些包是dll负责的,进而避免重复打包 ...(
    function () { let max = 2 let res = [] for (let i = 0; i < max; i++) { res.push(new webpack.DllReferencePlugin({ context: path.resolve(__dirname, '../'), manifest: require(resolve(`./dllManifest/vendor${i}-manifest.json`)) })) } return res })() ]

    在/build/webpack.dev.conf.js,/build/webpack.prod.conf.js文件HtmlWebpackPlugin实例中添加dll属性,方便在index.html中使用:

  4.     new HtmlWebpackPlugin({
          filename: 'index.html',
          template: 'index.html',
          inject: true,
          // ----------------------------------------------------
          dll: (function () {
            let max = 2
            let res = []
            for (let i = 0; i < max; i++) {
              const dllName = require(path.resolve(__dirname, `.././dllManifest/vendor${i}-manifest.json`)).name.split('_')
              res.push(`/static/dll/${dllName[0]}.${dllName[1]}.dll.js`)
            }
            return res
          })()
          // ----------------------------------------------------
        })

    修改/index.html模板:

        <!-- 要注意文件注入的位置,以免其他js运行前,找不到相关依赖 -->
        <% for (let i of htmlWebpackPlugin.options.dll) { %>
          <script src="<%= i %>"></script>
        <% } %>

     

本次主要解决的问题是:每次代码改动重新打包花费时间过长的问题。

解决是通过webpack提供的DllPlugin完成,包括dll打包的js文件命名加上hash,以及避免每次打包需手动修改index.html模板的问题。

 

posted @ 2017-12-15 16:48  仰戈  阅读(3603)  评论(0编辑  收藏  举报