DllPlugin

2023-06-02 14:43 更新

?DllPlugin? 和 ?DllReferencePlugin? 用某種方法實現(xiàn)了拆分 bundles,同時還大幅度提升了構(gòu)建的速度。"DLL" 一詞代表微軟最初引入的動態(tài)鏈接庫。

DllPlugin

此插件用于在單獨的 webpack 配置中創(chuàng)建一個 dll-only-bundle。 此插件會生成一個名為 ?manifest.json? 的文件,這個文件是用于讓 ?DllReferencePlugin? 能夠映射到相應的依賴上。

  • ?context?(可選): manifest 文件中請求的 context (默認值為 webpack 的 context)
  • ?format? (boolean = false):如果為 ?true?,則 manifest json 文件 (輸出文件) 將被格式化。
  • ?name?:暴露出的 DLL 的函數(shù)名(TemplatePaths:?[fullhash] & [name]? )
  • ?path?:manifest.json 文件的 絕對路徑(輸出文件)
  • ?entryOnly? (boolean = true):如果為 ?true?,則僅暴露入口
  • ?type?:dll bundle 的類型
new webpack.DllPlugin(options);

在給定的 ?path? 路徑下創(chuàng)建一個 ?manifest.json? 文件。這個文件包含了從 require 和 import 中 request 到模塊 id 的映射。 ?DllReferencePlugin? 也會用到這個文件。

此插件與 ?output.library? 的選項相結(jié)合可以暴露出(也稱為放入全局作用域)dll 函數(shù)。

DllReferencePlugin

此插件配置在 webpack 的主配置文件中,此插件會把 dll-only-bundles 引用到需要的預編譯的依賴中。

  • ?context?:(絕對路徑) manifest (或者是內(nèi)容屬性)中請求的上下文
  • ?extensions?:用于解析 dll bundle 中模塊的擴展名 (僅在使用 'scope' 時使用)。
  • ?manifest? :包含 ?content? 和 ?name? 的對象,或者是一個字符串 —— 編譯時用于加載 JSON manifest 的絕對路徑
  • ?content? (可選): 請求到模塊 id 的映射(默認值為 ?manifest.content?)
  • ?name? (可選):dll 暴露地方的名稱(默認值為 ?manifest.name?)(可參考externals
  • ?scope? (可選):dll 中內(nèi)容的前綴
  • ?sourceType? (可選):dll 是如何暴露的
new webpack.DllReferencePlugin(options);

通過引用 dll 的 manifest 文件來把依賴的名稱映射到模塊的 id 上,之后再在需要的時候通過內(nèi)置的 __webpack_require__ 函數(shù)來 require 對應的模塊

模式(Modes)

這個插件支持兩種模式,分別是作用域(scoped)和映射(mapped)。

Scoped Mode

dll 中的內(nèi)容可以使用模塊前綴的方式引用,舉例來說,設置 ?scope = 'xyz'?,這個 dll 中的名為 ?abc? 的文件可以通過 ?require('xyz/abc'?) 來獲取。

Mapped Mode

dll 中的內(nèi)容會被映射到當前目錄下。如果被 ?require? 的文件與 dll 中的某個文件匹配(解析之后),那么這個 dll 中的文件就會被使用。

由于這是在解析了 dll 中每個文件之后才觸發(fā)的,因此相同的路徑必須能夠確保這個 dll bundle 的使用者(不一定是人,可指某些代碼)有權(quán)限訪問。 舉例來說, 假如一個 dll bundle 中含有 ?loadash? 庫以及文件 ?abc?, 那么 ?require("lodash")? 和 ?require("./abc")?都不會被編譯進主 bundle 文件中,而是會被 dll 所使用。

用法(Usage)

webpack.vendor.config.js

const path = require('path');

new webpack.DllPlugin({
  context: __dirname,
  name: '[name]_[fullhash]',
  path: path.join(__dirname, 'manifest.json'),
});

webpack.app.config.js

new webpack.DllReferencePlugin({
  context: __dirname,
  manifest: require('./manifest.json'),
  scope: 'xyz',
  sourceType: 'commonjs2',
});

示例

Vendor 和 User

兩個單獨的用例,用來分別演示作用域(scope)和上下文(context)。

參考

Source

Tests

Further Reading


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號