从零开始的webpack生活-0x008:DLL加速编译

发布时间:2019-06-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了从零开始的webpack生活-0x008:DLL加速编译脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

0x001 概述

上一章讲的是CommonChunkPlugin,和这一章依旧没有丝毫关系,这一章讲的是DllPluginDllReferencePlugin

0x002 插件介绍

这个插件啊,用来预打包一些第三方库,因为他们不经常修改,而每次我们引用他们之后都要将他们不断的打包一次又一次,不但浪费了调试编译的时间,还浪费了....时间。

0x003 栗子又来了

  1. 初始化项目

    $ midkir 0x007-dll
    $ cd 0x007-dll
    $ cnpm inIT -y
    $ cnpm install Angular lodash jquery
  2. 这次需要两个配置文件,一个用于打包dll,一个用于打包dll-user,先配置用来打包dllwebpack.dll.config.js

    $ vim ./webpack.dll.config.js
    // ./webpack.dll.config.js
    const path = require('path');
    const webpack = require('webpack');
    
    module.exports = {
        entry: {
            vendor: ['angular', 'jquery','lodash']// 用这三个库打包成dll做测试
        },
        output: {
            path: path.join(__dirname, 'dist'),
            filename: '[name].dll.js',
            library: '[name]_library'
        },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'dist', '[name]-manifest.json'),
                name: '[name]_library' // 需要与output.library相同
            })
        ]
    };
  3. 打包dll,将会在./dist目录下生成vendor-minifest.jsonvendor.dll.js

    $ webpack --config webpack.dll.config.js 
  4. 配置dll-user

    $ vim ./webpack.config.js
    # ./webpack.config.js
    const path = require('path');
    const webpack = require('webpack');
    module.exports = {
        entry: {
            'dll-user': ['./src/index.js']
        },
        output: {
            path: path.join(__dirname, 'dist'),
            filename: '[name].bundle.js'
        },
    
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./dist/vendor-manifest.json')
            })
        ]
    
    };
    
  5. 添加入口文件

    $ vim ./src/index.js
    // ./src/index.js
    VAR angular = require('angular');
    console.LOG(angular);
  6. 打包dll-user

    $ webpack 
    Hash: 1aa3feec9d1827de7d5a
    Version: webpack 3.8.1
    Time: 70ms
                 Asset     Size  Chunks             Chunk names
    dll-user.bundle.js  2.88 kB       0  [emitted]  dll-user
       [0] multi ./src/index.js 28 bytes {0} [built]
       [2] ./src/index.js 56 bytes {0} [built]
       // 注意这行 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
       [3] delegated ./node_modules/_angular@1.6.6@angular/index.js From dll-reference vendor_library 42 bytes {0} [built]
        + 1 hidden module

    注意:这里我们引用了angular但是在打包完的index.js中,并不存在angular,因为我们通过引用dll来引入angular,在打包的信息输出中,对于angular的处理也变成了delegated,

  7. 更多详细信息,请查看webpack关于DllPlugin章节

0x004 资

脚本宝典总结

以上是脚本宝典为你收集整理的从零开始的webpack生活-0x008:DLL加速编译全部内容,希望文章能够帮你解决从零开始的webpack生活-0x008:DLL加速编译所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。