webpack4 dllplugin

dllplugin 動(dòng)態(tài)鏈接庫(kù),其實(shí)就是緩存,即事先把常用但又構(gòu)建時(shí)間長(zhǎng)的代碼提前打包好,(例如:react、react-dom),叫dll,后面再打包的時(shí)候就跳過(guò)原來(lái)的未打包代碼,直接用dll,這樣一來(lái),構(gòu)建時(shí)間就會(huì)縮短,提高webpack打包速度。

即用空間換時(shí)間。


image.png

第一步:

// 文件目錄:configs/webpack.dll.js

'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
    mode: 'production',
    entry: {
        react: ['react', 'react-dom'],
    },
    // 這個(gè)是輸出 dll 文件
    output: {
        path: path.resolve(__dirname, '../dll'),
        filename: '_dll_[name].js',
        library: '_dll_[name]',
    },
    // 這個(gè)是輸出映射表
    plugins: [
        new webpack.DllPlugin({ 
            name: '_dll_[name]', // name === output.library
            path: path.resolve(__dirname, '../dll/[name].manifest.json'),
        })
    ]
};

第二步:

// package.json

{
  "scripts": {
    "build:dll": "webpack --config configs/webpack.dll.js",
  },
}

第三步:webpack.config.js


const path = require('path');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin'); // 顧名思義,把資源加到 html 里,那這個(gè)插件把 dll 加入到 index.html 里
const webpack = require('webpack');
module.exports = {
  // ......
  plugins: [
    new webpack.DllReferencePlugin({
      // 注意: DllReferencePlugin 的 context 必須和 package.json 的同級(jí)目錄,要不然會(huì)鏈接失敗
      context: path.resolve(__dirname, '../'),
      manifest: path.resolve(__dirname, '../dll/react.manifest.json'),
    }),
    new AddAssetHtmlPlugin({
      filepath: path.resolve(__dirname, '../dll/_dll_react.js'),
    }),
  ]
}

AutoDllPlugin

autodll-webpack-plugin簡(jiǎn)化dllplugin配置。

const path = require('path');
const AutoDllPlugin = require('autodll-webpack-plugin'); // 第 1 步:引入 DLL 自動(dòng)鏈接庫(kù)插件

module.exports = {
  // ......
  plugins: [
        // 第 2 步:配置要打包為 dll 的文件
        new AutoDllPlugin({
            inject: true, // 設(shè)為 true 就把 DLL bundles 插到 index.html 里
            filename: '[name].dll.js',
            context: path.resolve(__dirname, '../'), // AutoDllPlugin 的 context 必須和 package.json 的同級(jí)目錄,要不然會(huì)鏈接失敗
            entry: {
                react: [
                    'react',
                    'react-dom'
                ]
            }
        })
  ]
}

拋棄 DLL:Vue & React 官方的共同選擇

因?yàn)?Webpack 4 的打包性能足夠好的,dll 沒(méi)有在 Vue ClI 里繼續(xù)維護(hù)的必要了。

比 DLL 更優(yōu)秀的插件HardSourceWebpackPlugin

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
  // ......
  plugins: [
    new HardSourceWebpackPlugin() // <- 直接加入這行代碼就行
  ]
}

參考資料:
https://www.cnblogs.com/skychx/p/webpack-dllplugin.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容