從零開始的webpack生活-0x008:DLL加速編譯

0x001 概述

上一章講的是CommonChunkPlugin,和這一章依舊沒有絲毫關係,這一章講的是DllPluginDllReferencePluginnode

0x002 插件介紹

這個插件啊,用來預打包一些第三方庫,由於他們不常常修改,而每次咱們引用他們以後都要將他們不斷的打包一次又一次,不但浪費了調試編譯的時間,還浪費了....時間。jquery

0x003 栗子又來了

  1. 初始化項目webpack

    $ midkir 0x007-dll
    $ cd 0x007-dll
    $ cnpm init -y
    $ cnpm install angular lodash jquery
  2. 此次須要兩個配置文件,一個用於打包dll,一個用於打包dll-user,先配置用來打包dllwebpack.dll.config.jsgit

    $ 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.jsgithub

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

    $ 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. 添加入口文件npm

    $ vim ./src/index.js
    // ./src/index.js
    var angular = require('angular');
    console.log(angular);
  6. 打包dll-userjson

    $ 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,vim

  7. 更多詳細信息,請查看webpack關於DllPlugin章節

0x004 資源

相關文章
相關標籤/搜索