CC 4.0 授權

本節內容源自以下連結的內容,並受 CC BY 4.0 授權條款約束。

以下內容若未特別聲明,則可視為在原始內容基礎上進行修改和刪除的結果。

輸出

頂層的 `output` 鍵包含一組選項,指示 Rspack 如何以及在何處輸出您的 bundle、資源,以及您使用 Rspack 打包或載入的其他任何內容。

  • 類型: 物件

output.assetModuleFilename

  • 類型: string | ((pathData: PathData, assetInfo?: JsAssetInfo) => string)
  • 預設值: '[hash][ext][query]'

output.filename 相同,但用於 資源模組

對於從資料 URI 替換建立的資源,[name][file][query][fragment][base][path] 會設定為空字串。

資源模組要輸出的檔案名稱。此值可被 Rule.generator.filename 覆寫。

將資源模組輸出為單獨的檔案

output.asyncChunks

  • 類型: boolean
  • 預設值: true

建立按需載入的非同步 chunk。

output.charset

  • 類型: boolean
  • 預設值: true

charset="utf-8" 新增至 HTML <script> 標籤。

提示

雖然 <script> 標籤的 charset 屬性已棄用,但 rspack 仍然預設新增它,以便與非現代瀏覽器相容。

output.chunkFilename

  • 類型: string = '[id].js' | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 預設值:output.filename 決定(當它不是函式時),否則為 '[id].js'

此選項決定非初始 chunk 檔案的名稱。 有關可能的值的詳細資訊,請參閱 output.filename 選項。

請注意,這些檔案名稱需要在執行時產生,以傳送 chunk 的請求。 因此,像 [name][chunkhash] 這樣的佔位符需要使用 Rspack 運行時將 chunk id 到佔位符值的對應新增到輸出 bundle 中。 這會增加大小,並且當任何 chunk 的佔位符值變更時,可能會使 bundle 失效。

預設情況下,使用 [id].js 或從 output.filename 推斷的值([name][id] 取代或 [id]. 被前置)。

rspack.config.js
module.exports = {
  //...
  output: {
    //...
    chunkFilename: '[id].js',
  },
};

作為函式使用

rspack.config.js
module.exports = {
  //...
  output: {
    chunkFilename: pathData => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};

output.chunkFormat

  • 類型: false | 'array-push' | 'commonjs' | 'module' | string
  • 預設值:targetoutput.module決定

區塊的格式(預設包含的格式有 'array-push' (web/webworker)、'commonjs' (node.js)、'module' (ESM),但其他格式可能會由插件加入)。

提示

此選項的預設值取決於targetoutput.module設定。更多詳細資訊,請在Rspack 預設值中搜尋 "chunkFormat"。

rspack.config.js
module.exports = {
  output: {
    chunkFormat: 'commonjs',
  },
};

output.chunkLoadTimeout

  • 類型: number
  • 預設值: 120000

區塊請求逾時前的毫秒數。

rspack.config.js
module.exports = {
  //...
  output: {
    //...
    chunkLoadTimeout: 30000, // 30 seconds before chunk request timed out.
  },
};

output.chunkLoadingGlobal

Rspack 用於載入區塊的全域變數。

rspack.config.js
module.exports = {
  output: {
    chunkLoadingGlobal: 'myCustomFunc',
  },
};

output.chunkLoading

  • 類型: false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import'

載入區塊的方法(預設包含的方法有 'jsonp' (web)、'import' (ESM)、'importScripts' (webworker)、'require' (同步 node.js)、'async-node' (非同步 node.js),但其他方法可能會由插件加入)。預設值將根據targetchunkFormat的配置決定。

提示

此選項的預設值取決於targetchunkFormat設定。更多詳細資訊,請在Rspack 預設值中搜尋 "chunkLoading"

rspack.config.js
module.exports = {
  output: {
    chunkLoading: 'async-node',
  },
};

output.clean

  • 類型: boolean
  • 預設值: false

在產生產品之前,刪除輸出目錄中的所有檔案。

rspack.config.js
module.exports = {
  //...
  output: {
    clean: true, // Clean the output directory before emit.
  },
};

output.compareBeforeEmit

  • 類型: boolean
  • 預設值: true

告知 Rspack 在寫入輸出檔案系統之前,檢查要發出的檔案是否已存在並且具有相同內容。

警告

當磁碟上已存在具有相同內容的檔案時,Rspack 將不會寫入輸出檔案。

rspack.config.js
module.exports = {
  //...
  output: {
    compareBeforeEmit: false,
  },
};

output.crossOriginLoading

  • 類型: false | 'anonymous' | 'use-credentials'
  • 預設值: false

crossOriginLoading 配置可讓您為動態載入的區塊設定crossorigin 屬性

如果 target'web',Rspack 將動態建立 <script><link> 標籤來載入非同步 JavaScript 和 CSS 資源。如果這些資源的 URL 在其他網域上,且 crossOriginLoading 不為 false,Rspack 將會將 crossorigin 屬性加入至 <script><link> 標籤。

可選值

crossOriginLoading 具有下列可選值

  • false:不要設定crossorigin 屬性
  • 'anonymous':將 crossorigin 設定為 'anonymous',以啟用不使用使用者憑證的跨來源。
  • 'use-credentials':將 crossorigin 設定為 'use-credentials',以啟用使用使用者憑證的跨來源。

範例

例如,將 output.publicPath 設定為 https://example.com/ 並將 output.crossOriginLoading 設定為 'anonymous'

rspack.config.js
const path = require('path');

module.exports = {
  output: {
    publicPath: 'https://example.com/',
    crossOriginLoading: 'anonymous',
  },
};

當 Rspack 動態載入 JavaScript 資源時,它將產生下列 HTML

<script src="https://example.com/foo.js" crossorigin="anonymous"></script>

output.cssChunkFilename

  • 類型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 預設值:output.chunkFilename不是函式時,由其決定,否則為 '[id].css'

此選項決定磁碟上非初始 CSS 輸出檔案的名稱。請參閱output.filename選項以了解可能的值的詳細資訊。

不得在此指定絕對路徑。但是,您可以隨意包含以 '/' 分隔的資料夾。此指定的路徑會與output.path值結合,以精確指出磁碟上的位置。

output.cssFilename

  • 類型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 預設值:output.filename決定

此選項決定磁碟上 CSS 輸出檔案的名稱。請參閱output.filename選項以了解可能的值的詳細資訊。

不得在此指定絕對路徑。但是,您可以隨意包含以 '/' 分隔的資料夾。此指定的路徑會與output.path值結合,以精確指出磁碟上的位置。

output.devtoolFallbackModuleFilenameTemplate

  • 類型: string | function (info)
  • 預設值: undefined

當上述範本字串或函式產生重複項時,會使用備用方案。

請參閱output.devtoolModuleFilenameTemplate

output.devtoolModuleFilenameTemplate

  • 類型: string = 'webpack://[namespace]/[resource-path]?[loaders]' | function (info) => string
  • 預設值: undefined

僅當devtool使用需要模組名稱的選項時,才會使用此選項。

自訂每個來源對應的 sources 陣列中使用的名稱。這可以透過傳遞範本字串或函式來完成。例如,當使用 devtool: 'eval' 時。

rspack.config.js
module.exports = {
  //...
  output: {
    devtoolModuleFilenameTemplate:
      'webpack://[namespace]/[resource-path]?[loaders]',
  },
};

範本字串中可使用下列替換

範本 描述
[absolute-resource-path] 絕對檔名
[all-loaders] 自動和明確的載入器和參數,直到第一個載入器的名稱
[hash] 模組識別碼的雜湊
[id] 模組識別碼
[loaders] 明確的載入器和參數,直到第一個載入器的名稱
[resource] 用於解析檔案的路徑,以及在第一個載入器上使用的任何查詢參數
[resource-path] 用於解析檔案的路徑,不包含任何查詢參數
[namespace] 模組命名空間。這通常是作為程式庫建置時的程式庫名稱,否則為空

當使用函式時,相同的選項會透過 info 參數以駝峰式大小寫提供

rspack.config.js
module.exports = {
  //...
  output: {
    devtoolModuleFilenameTemplate: info => {
      return `webpack:///${info.resourcePath}?${info.loaders}`;
    },
  },
};

如果多個模組會產生相同的名稱,則會改為對這些模組使用output.devtoolFallbackModuleFilenameTemplate

output.devtoolNamespace

  • 類型: string
  • 預設值: undefined

此選項決定與output.devtoolModuleFilenameTemplate搭配使用的模組命名空間。如果未指定,則會預設為:output.uniqueName的值。它用於防止當載入使用 Rspack 建置的多個程式庫時,原始程式碼對應中的來源檔案路徑衝突。

例如,如果您有 2 個程式庫,命名空間分別為 library1library2,且兩者都有一個檔案 ./src/index.js(內容可能不同),它們將會將這些檔案公開為 webpack://library1/./src/index.jswebpack://library2/./src/index.js

output.enabledChunkLoadingTypes

入口點允許使用的區塊載入類型清單。將由 Rspack 自動填入。僅當使用函式作為入口選項並從那裡傳回 chunkLoading 選項時才需要。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledChunkLoadingTypes: ['jsonp', 'require'],
  },
};

output.enabledLibraryTypes

入口點允許使用的程式庫類型清單。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledLibraryTypes: ['module'],
  },
};

output.enabledWasmLoadingTypes

入口點允許使用的 Wasm 載入類型清單。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledWasmLoadingTypes: ['fetch'],
  },
};

output.environment

告訴 Rspack 在產生的執行階段程式碼中可以使用哪種 ES 功能。

rspack.config.js
module.exports = {
  output: {
    environment: {
      // The environment supports arrow functions ('() => { ... }').
      arrowFunction: true,
      // The environment supports async function and await ('async function () { await ... }').
      asyncFunction: true,
      // The environment supports BigInt as literal (123n).
      bigIntLiteral: false,
      // The environment supports const and let for variable declarations.
      const: true,
      // The environment supports destructuring ('{ a, b } = obj').
      destructuring: true,
      // The environment supports 'document' variable.
      document: true,
      // The environment supports an async import() function to import EcmaScript modules.
      dynamicImport: false,
      // The environment supports an async import() when creating a worker, only for web targets at the moment.
      dynamicImportInWorker: false,
      // The environment supports 'for of' iteration ('for (const x of array) { ... }').
      forOf: true,
      // The environment supports 'globalThis'.
      globalThis: true,
      // The environment supports ECMAScript Module syntax to import ECMAScript modules (import ... from '...').
      module: false,
      // Determines if the node: prefix is generated for core module imports in environments that support it.
      // This is only applicable to Webpack runtime code.
      nodePrefixForCoreModules: false,
      // The environment supports optional chaining ('obj?.a' or 'obj?.()').
      optionalChaining: true,
      // The environment supports template literals.
      templateLiteral: true,
    },
  },
};

output.filename

  • 類型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 預設值:[output.module](#outputmodule)true 時,此選項為 '[name].mjs',否則為 '[name].js'

此選項決定每個輸出捆綁包的名稱。該捆綁包會被寫入 output.path 選項指定的目錄中。

對於單一的 entry 點,這可以是一個靜態名稱。

rspack.config.js
module.exports = {
  output: {
    filename: 'bundle.js',
  },
};

然而,當透過多個入口點、程式碼分割或各種外掛程式建立多個捆綁包時,您應該使用以下其中一種替換方式,為每個捆綁包提供唯一的名稱...

其他可以分割多個捆綁包的情況描述

Rspack 會對使用者輸入的程式碼執行程式碼分割最佳化,其中可能包含但不限於程式碼分割、捆綁包分割或透過其他外掛程式實現的分割。這些分割動作可能會導致產生多個捆綁包,因此捆綁包的檔案名稱需要動態產生。

使用 Entry 名稱

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[name].bundle.js',
  },
};

使用內部區塊 ID

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[id].bundle.js',
  },
};

使用從產生的內容產生的雜湊值

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[contenthash].bundle.js',
  },
};

合併多種替換方式

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[name].[contenthash].bundle.js',
  },
};

使用函式回傳檔案名稱

rspack.config.js
module.exports = {
  //...
  output: {
    filename: pathData => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};

請注意,此選項稱為 filename,但您仍然可以使用類似 'js/[name]/bundle.js' 的方式來建立資料夾結構。

請注意,此選項不會影響按需載入區塊的輸出檔案。它只會影響最初載入的輸出檔案。對於按需載入的區塊檔案,會使用 output.chunkFilename 選項。由 loader 建立的檔案也不會受到影響。在這種情況下,您必須嘗試特定 loader 的可用選項。

樣板字串

以下樣板字串可用於替換相應的檔案名稱。不同的上下文對應不同的可替換內容,例如 output.assetModuleFilename 支援使用 檔案上下文模組上下文

編譯上下文

可以在編譯層級替換的內容。

範本 描述
[fullhash] 編譯的完整雜湊值

區塊上下文

可以在區塊層級替換的內容。

樣板 描述
[id] 目前的區塊 ID
[name] 當區塊名稱存在時使用名稱,否則使用區塊 ID
[chunkhash] 區塊的雜湊值,從目前區塊中所有類型的元素計算得出
[contenthash] 區塊的雜湊值,從僅包含該類型內容的元素計算得出。例如,如果產生 JavaScript 類型的模組,則只會使用目前區塊中所有 JavaScript 類型模組的雜湊值。

模組上下文

可以在模組層級替換的內容。

範本 描述
[id] 模組的 ID
[hash] 模組的雜湊值
[contenthash] 模組內容的雜湊值

檔案上下文

可以在檔案層級替換的內容。

範本 描述
[file] 檔案名稱和路徑,不包含查詢或片段
[query] ? 開頭的查詢
[fragment] # 開頭的片段
[base] 僅檔案名稱 (包含副檔名),不包含路徑
[filebase] 相同,但已棄用
[path] 僅路徑,不包含檔案名稱
[name] 僅檔案名稱,不包含副檔名或路徑
[ext] . 開頭的副檔名 (不適用於 output.filename)

可在 URL 層級使用的替換

範本 描述
[url] URL
提示

[file] 等於 [path][base][base] 等於 [name][ext]。完整路徑為 [path][name][ext][query][fragment][path][base][query][fragment][file][query][fragment]

雜湊值 ([hash][contenthash][chunkhash]) 的長度可以使用 [hash:12] 指定 (預設為 16)。或者,指定 output.hashDigestLength 來全域設定長度。

當您想在實際檔案名稱中使用其中一個預留位置時,可以篩選掉預留位置的替換。例如,若要輸出檔案 [name].js,您必須在方括號之間新增反斜線來跳脫 [name] 預留位置。因此,[\name\] 會產生 [name],而不是被替換為資產的 name

範例:[\id\] 會產生 [id],而不是被替換為 id

如果此選項使用函式,則該函式將會傳遞一個物件,其中包含上表中替換所需的資料。替換也會套用至回傳的字串。傳遞的物件將具有以下類型:(可用屬性取決於上下文)

type PathData = {
  hash: string;
  hashWithLength: (number) => string;
  chunk: Chunk | ChunkPathData;
  module: Module | ModulePathData;
  contentHashType: string;
  contentHash: string;
  contentHashWithLength: (number) => string;
  filename: string;
  url: string;
  runtime: string | SortableSet<string>;
  chunkGraph: ChunkGraph;
};
type ChunkPathData = {
  id: string | number;
  name: string;
  hash: string;
  hashWithLength: (number) => string;
  contentHash: Record<string, string>;
  contentHashWithLength: Record<string, (number) => string>;
};
type ModulePathData = {
  id: string | number;
  hash: string;
  hashWithLength: (number) => string;
};

output.globalObject

  • 類型: string
  • 預設值: 'self'

當目標是程式庫時,特別是當 library.type'umd' 時,此選項會指示將使用哪個全域物件來掛載程式庫。為了讓 UMD 建置同時在瀏覽器和 Node.js 上可用,請將 output.globalObject 選項設定為 'this'。對於類似 Web 的目標,預設值為 self

您的入口點的回傳值將會使用 output.library.name 的值指派給全域物件。根據 type 選項的值,全域物件可能會分別變更,例如 selfglobalglobalThis

例如

rspack.config.js
module.exports = {
  // ...
  output: {
    library: 'myLib',
    libraryTarget: 'umd',
    filename: 'myLib.js',
    globalObject: 'this',
  },
};

output.hashDigest

  • 類型: string
  • 預設值: 'hex'

產生雜湊值時要使用的編碼。將 'base64' 用於檔案名稱可能會產生問題,因為其字母包含字元 /。同樣地,'latin1' 可能包含任何字元。

output.hashDigestLength

  • 類型: number
  • 預設值: 16

要使用的雜湊值摘要前置長度。

output.hashFunction

  • 類型: 'md4' | 'xxhash64'
  • 預設值: 'xxhash64'

要使用的雜湊演算法。

rspack.config.js
module.exports = {
  //...
  output: {
    hashFunction: 'xxhash64',
  },
};
提示

Rspack 自 v1.1 起預設使用速度較快的 xxhash64 演算法。

output.hashSalt

  • 類型: string
  • 預設值: undefined

用於更新雜湊值的可選鹽值。

output.hotUpdateChunkFilename

  • 類型: string
  • 預設值: "[id].[fullhash].hot-update.js"

自訂熱更新區塊的檔案名稱。請參閱 output.filename 選項以了解可能值的詳細資訊。

這裡只允許使用 [id][fullhash] 預留位置,預設值為

rspack.config.js
module.exports = {
  //...
  output: {
    hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
  },
};
提示

通常您不需要變更 output.hotUpdateChunkFilename

output.hotUpdateGlobal

  • 類型: string
  • 預設值: "webpackHotUpdate" + output.uniqueName

僅當 target 設定為 'web' 時才會使用,該設定使用 JSONP 來載入熱更新。

JSONP 函式用於非同步載入熱更新區塊。

如需詳細資訊,請參閱 output.chunkLoadingGlobal

output.hotUpdateMainFilename

  • 類型: string
  • 預設值: "[runtime].[fullhash].hot-update.json"

自訂主要熱更新檔案名稱。[fullhash][runtime] 可用作預留位置。

提示

通常您不需要變更 output.hotUpdateMainFilename

output.iife

  • 類型: boolean
  • 預設值: true

告知 Rspack 在發出的程式碼周圍新增 IIFE 包裝器。

rspack.config.js
module.exports = {
  //...
  output: {
    iife: true,
  },
};

output.importFunctionName

  • 類型: string
  • 預設值: 'import'

原生 import() 函式的名稱。可用於 polyfilling,例如使用 dynamic-import-polyfill

rspack.config.js
module.exports = {
  //...
  output: {
    importFunctionName: '__import__',
  },
};

output.importMetaName

  • 類型: string
  • 預設值: 'import.meta'

原生 import.meta 物件的名稱 (可以交換為 polyfill)。

rspack.config.js
module.exports = {
  //...
  output: {
    importMetaName: 'pseudoImport.meta',
  },
};

output.library

輸出一個程式庫,公開您的入口點的匯出。

  • 類型: string | string[] | object

讓我們看一個範例。

rspack.config.js
module.exports = {
  // …
  entry: './src/index.js',
  output: {
    library: 'MyLibrary',
  },
};

假設您在 src/index.js 入口點中匯出了一個函式

export function hello(name) {
  console.log(`hello ${name}`);
}

現在,變數 MyLibrary 將會與您的入口檔案的匯出綁定,以下是如何使用 Rspack 捆綁的程式庫

<script src="https://example.org/path/to/my-library.js"></script>
<script>
  MyLibrary.hello('rspack');
</script>

在上述範例中,我們將單一入口檔案傳遞給 entry,但是,Rspack 可以接受多種入口點,例如 arrayobject

  1. 如果您提供一個 array 作為 entry 點,則只會公開陣列中的最後一個。

    module.exports = {
      // …
      entry: ['./src/a.js', './src/b.js'], // 只有在 b.js 中导出的内容才会被暴露
      output: {
        library: 'MyLibrary',
      },
    };
  2. 如果提供一個 object 作為 entry 點,則可以使用 libraryarray 語法公開所有項目

    module.exports = {
      // …
      entry: {
        a: './src/a.js',
        b: './src/b.js',
      },
      output: {
        filename: '[name].js',
        library: ['MyLibrary', '[name]'], // name is a placeholder here
      },
    };

    假設 a.jsb.js 都匯出了一個函式 hello,以下是如何使用程式庫

    <script src="https://example.org/path/to/a.js"></script>
    <script src="https://example.org/path/to/b.js"></script>
    <script>
      MyLibrary.a.hello('rspack');
      MyLibrary.b.hello('rspack');
    </script>

output.library.amdContainer

  • 類型: string

在 AMD 模組中使用容器(定義於全域空間)來呼叫 define/require 函式。

警告

請注意,amdContainer 的值必須設定為全域變數。

rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      amdContainer: 'window["clientContainer"]',
      type: 'amd', // or 'amd-require'
    },
  },
};

這將會產生以下打包結果

window['clientContainer'].define(/*define args*/); // or 'amd-require' window['clientContainer'].require(/*require args*/);

output.library.name

指定程式庫的名稱。

  • 類型: string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
    },
  },
};

output.library.type

設定如何暴露程式庫。

  • 類型: string

    預設包含的類型有 'var''module''system''assign''assign-properties''this''window''self''global''commonjs''commonjs2''commonjs-module''commonjs-static''amd''amd-require''umd''umd2',但其他類型可能會由外掛程式加入。

在以下範例中,我們將使用 _entry_return_ 來表示進入點所回傳的值。

暴露變數

這些選項會將進入點的回傳值(例如進入點輸出的任何內容)指派給 output.library.name 所提供的名稱,且該名稱的作用域是該捆綁包被包含的作用域。

類型:'var'
rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
    },
  },
};

當您的程式庫載入時,您的進入點的回傳值將會指派給一個變數

var MyLibrary = _entry_return_;

// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();
類型:'assign'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign',
    },
  },
};

這會產生一個隱含的全域變數,該變數有可能重新指派現有的值(請謹慎使用)

MyLibrary = _entry_return_;

請注意,如果 MyLibrary 沒有較早定義,您的程式庫將會設定在全域作用域中。

類型:'assign-properties'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign-properties',
    },
  },
};

type: 'assign' 類似,但更安全的選項,因為它會重複使用現有的 MyLibrary

// only create MyLibrary if it doesn't exist
MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;
// then copy the return value to MyLibrary
// similarly to what Object.assign does

// for instance, you export a `hello` function in your entry as follow
export function hello(name) {
  console.log(`Hello ${name}`);
}

// In another script with MyLibrary loaded
// you can run `hello` function like so
MyLibrary.hello('World');

透過物件指派暴露

這些選項會將進入點的回傳值(例如進入點輸出的任何內容)指派給 output.library.name 所定義名稱下的特定物件。

類型:'this'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'this',
    },
  },
};

您的進入點的回傳值將會指派給 this,屬性名稱由 output.library.name 指定。this 的意義由您決定

this['MyLibrary'] = _entry_return_;

// In a separate script
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if `this` is window
類型:'window'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'window',
    },
  },
};

您的進入點的回傳值將會使用 output.library.name 的值指派給 window 物件。

window['MyLibrary'] = _entry_return_;

window.MyLibrary.doSomething();
類型:'global'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'global',
    },
  },
};

您的進入點的回傳值將會使用 output.library.name 的值指派給全域物件。根據 target 值,全域物件可能會相應變更,例如 selfglobalglobalThis

global['MyLibrary'] = _entry_return_;

global.MyLibrary.doSomething();
類型:'commonjs'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'commonjs',
    },
  },
};

您的進入點的回傳值將會使用 output.library.name 的值指派給 exports 物件。顧名思義,這會在 CommonJS 環境中使用。

exports['MyLibrary'] = _entry_return_;

require('MyLibrary').doSomething();
警告

請注意,如果未設定 output.library.name,進入點回傳的所有屬性都會指派給指定的物件;不會檢查現有的屬性名稱。

模組定義系統

這些選項會產生一個帶有完整標頭的捆綁包,以確保與各種模組系統的相容性。output.library.name 選項會在以下 output.library.type 選項下採用不同的意義。

類型:'module'
rspack.config.js
module.exports = {
  // …
  experiments: {
    outputModule: true,
  },
  output: {
    library: {
      // do not specify a `name` here
      type: 'module',
    },
  },
};

輸出 ES 模組。

然而,此功能仍處於實驗階段,尚未完全支援,因此請務必預先啟用 experiments.outputModule。此外,您可以在此討論串中追蹤開發進度。

類型:'commonjs2'
module.exports = {
  // …
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs2',
    },
  },
};

您的進入點的回傳值將會指派給 module.exports。顧名思義,這會在 Node.js (CommonJS) 環境中使用

module.exports = _entry_return_;

require('MyLibrary').doSomething();

如果我們使用 type: commmonjs2 指定 output.library.name,您的進入點的回傳值將會指派給 module.exports.[output.library.name]

提示

想知道 CommonJS 和 CommonJS2 之間的差異嗎?雖然它們很相似,但在 Rspack 的環境中通常不相關的細微差異。(如需更多詳細資訊,請閱讀此問題。)

類型:'commonjs-static'
module.exports = {
  // …
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs-static',
    },
  },
};

個別匯出將會設定為 module.exports 的屬性。名稱中的「static」指的是輸出是可靜態分析的,因此具名匯出可透過 Node.js 匯入 ESM

輸入

export function doSomething() {}

輸出

function doSomething() {}

// …

exports.doSomething = __webpack_exports__.doSomething;

使用方式 (CommonJS)

const { doSomething } = require('./output.cjs'); // doSomething => [Function: doSomething]

使用方式 (ESM)

import { doSomething } from './output.cjs'; // doSomething => [Function: doSomething]
提示

當原始碼以 ESM 撰寫,且輸出應與 CJS 和 ESM 相容時,這會很有用。如需更多詳細資訊,請閱讀此問題此文章(特別是此章節)。

類型:'amd'

這會將您的程式庫暴露為 AMD 模組。

AMD 模組需要使用特定的屬性定義進入點區塊(例如 <script> 標籤載入的第一個指令碼),例如 definerequire,通常由 RequireJS 或任何相容的載入器(例如 almond)提供。否則,直接載入產生的 AMD 捆綁包會導致類似 define is not defined 的錯誤。

使用以下設定

rspack.config.js
module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd',
    },
  },
};

產生的輸出將使用名稱 "MyLibrary" 定義,即

define('MyLibrary', [], function () {
  return _entry_return_;
});

捆綁包可以作為指令碼標籤的一部分包含在內,並且可以使用以下方式叫用捆綁包

require(['MyLibrary'], function (MyLibrary) {
  // Do something with the library...
});

如果 output.library.name 未定義,則會改為產生以下內容。

define(function () {
  return _entry_return_;
});

如果直接使用 <script> 標籤載入,此捆綁包將無法如預期運作,甚至完全無法運作(如果是 almond 載入器)。它只會透過 RequireJS 相容的非同步模組載入器,透過該檔案的實際路徑運作,因此如果這些直接在伺服器上公開,output.pathoutput.filename 對於此特定設定可能變得重要。

類型:'amd-require'
rspack.config.js
module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd-require',
    },
  },
};

這會使用立即執行的 AMD require(dependencies, factory) 包裝函式包裝您的輸出。

'amd-require' 類型允許使用 AMD 相依性,而不需要稍後單獨叫用。與 'amd' 類型一樣,這取決於在載入 Rspack 輸出的環境中是否有適當的 require 函式

使用此類型時,無法使用程式庫名稱。

類型:'umd'

這會在所有模組定義下暴露您的程式庫,使其能夠與 CommonJS、AMD 和全域變數一起運作。請瀏覽 UMD 儲存庫以了解更多資訊。

在這種情況下,您需要 library.name 屬性來命名您的模組

module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
    },
  },
};

最後,輸出為

(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  else root['MyLibrary'] = factory();
})(global, function () {
  return _entry_return_;
});

請注意,省略 library.name 會導致進入點回傳的所有屬性直接指派給根物件,如物件指派章節中所述。範例

module.exports = {
  //...
  output: {
    libraryTarget: 'umd',
  },
};

輸出將會是

(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else {
    var a = factory();
    for (var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  }
})(global, function () {
  return _entry_return_;
});

您可以為 library.name 指定一個物件,以便為每個目標使用不同的名稱

module.exports = {
  //...
  output: {
    library: {
      name: {
        root: 'MyLibrary',
        amd: 'my-library',
        commonjs: 'my-common-library',
      },
      type: 'umd',
    },
  },
};
類型:'system'

這會將您的程式庫暴露為 System.register 模組。

System 模組需要在執行 Rspack 捆綁包時,在瀏覽器中存在全域變數 System。編譯為 System.register 格式可讓您使用 System.import('/bundle.js'),而無需額外設定,並將您的 Rspack 捆綁包載入 System 模組登錄。

module.exports = {
  //...
  output: {
    library: {
      type: 'system',
    },
  },
};

輸出

System.register([], function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
  return {
    execute: function () {
      // ...
    },
  };
});

除了將 output.library.type 設定為 system 之外,還將 output.library.name 新增至設定,輸出捆綁包會將程式庫名稱作為 System.register 的引數

System.register(
  'MyLibrary',
  [],
  function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
    return {
      execute: function () {
        // ...
      },
    };
  },
);

其他類型

類型:'jsonp'

rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'jsonp',
    },
  },
};

這會將您的進入點的回傳值包裝到 jsonp 包裝函式中。

MyLibrary(_entry_return_);

您的程式庫的相依性將由 externals 設定定義。

output.library.export

指定應將哪個匯出項暴露為程式庫。

  • 類型: string | string[]
  • 預設值: undefined

預設為 undefined,這會匯出整個 (命名空間) 物件。以下範例示範使用 output.library.type: 'var' 時此設定的效果。

rspack.config.js
module.exports = {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: 'default',
    },
  },
};

您的進入點的預設匯出將會指派給程式庫名稱

// If your library has a default export
var MyLibrary = _entry_return_.default;

您也可以將陣列傳遞給 output.library.export,這會解讀為要指派給程式庫名稱的模組路徑

rspack.config.js
module.exports = {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: ['default', 'subModule'],
    },
  },
};

這是程式庫程式碼

var MyLibrary = _entry_return_.default.subModule;

output.library.auxiliaryComment

在 UMD 包裝函式中新增註解。

  • 類型: string | { amd?: string, commonjs?: string, commonjs2?: string, root?: string }
  • 預設值: undefined

若要為每個 umd 類型插入相同的註解,請將 auxiliaryComment 設定為字串

module.exports = {
  // …
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: 'Test Comment',
    },
  },
};

這會產生以下內容

(function webpackUniversalModuleDefinition(root, factory) {
  //Test Comment
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  //Test Comment
  else if (typeof define === 'function' && define.amd) define([], factory);
  //Test Comment
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  //Test Comment
  else root['MyLibrary'] = factory();
})(self, function () {
  return _entry_return_;
});

若要進行精細控制,請傳遞物件

module.exports = {
  // …
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: {
        root: 'Root Comment',
        commonjs: 'CommonJS Comment',
        commonjs2: 'CommonJS2 Comment',
        amd: 'AMD Comment',
      },
    },
  },
};

output.library.umdNamedDefine

  • 類型: boolean
  • 預設值: undefined

當使用 output.library.type: "umd" 時,將 output.library.umdNamedDefine 設定為 true 會命名 UMD 建置的 AMD 模組。否則,會使用匿名 define

module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      umdNamedDefine: true,
    },
  },
};

AMD 模組將會是

define('MyLibrary', [], factory);

output.module

  • 類型: boolean
  • 預設值: false

將 JavaScript 檔案輸出為模組類型。預設為停用,因為這是一項實驗性功能。若要使用它,您必須將 experiments.outputModule 設定為 true

啟用後,Rspack 將會內部設定 output.iifefalseoutput.scriptType'module',並設定 terserOptions.moduletrue

如果您使用 Rspack 編譯一個要給其他人使用的函式庫,請確保當 output.moduletrue 時,將 output.libraryTarget 設定為 'module'

rspack.config.js
module.exports = {
  //...
  experiments: {
    outputModule: true,
  },
  output: {
    module: true,
  },
};

output.path

  • 類型: string
  • 預設值: path.resolve(process.cwd(), 'dist')

輸出目錄的 絕對路徑。

rspack.config.js
const path = require('path');

module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist/assets'),
  },
};

請注意,此參數中的 [fullhash] 將被替換為編譯的雜湊值。

警告

路徑不得包含驚嘆號 (!),因為 Rspack 將其保留給 loader 語法使用。

output.pathinfo

  • 類型: boolean | 'verbose'
  • 預設值: true

告訴 Rspack 在 bundles 中加入關於包含模組的資訊的註解。此選項在 development 模式下預設為 true,在 production 模式下則預設為 false'verbose' 會顯示更多資訊,例如 exports、執行時需求和 bailouts。

警告

雖然這些註解提供的資料在開發期間閱讀產生的程式碼時很有用,但不應該在生產環境中使用。

rspack.config.js
module.exports = {
  //...
  output: {
    pathinfo: true,
  },
};
提示

它還會在產生的 bundle 中加入一些關於 tree shaking 的資訊。

output.publicPath

  • 類型: 'auto' | string | ((pathData: PathData, assetInfo?: JsAssetInfo) => string)
  • 預設值:targets'web''webworker' 時為 'auto'。否則為 undefined

此選項決定了引用資源(例如:圖片、檔案等)的 URL 前綴。

例如,給定一個設定檔。

rspack.config.js
module.exports = {
  output: {
    publicPath: '/assets/',
    chunkFilename: '[id].chunk.js',
    assetModuleFilename: '[name][ext]',
  },
};

對於非初始 chunk 檔案,其請求 URL 看起來會像這樣:/assets/1.chunk.js

對於圖片的引用,請求 URL 看起來會像這樣:/assets/logo.png

此外,當您使用 CDN 部署產品時,它也很有用

rspack.config.js
module.exports = {
  output: {
    publicPath: 'https://cdn.example.com/assets/',
    assetModuleFilename: '[name][ext]',
  },
};

對於所有資源,它們的請求 URL 看起來會像這樣:https://cdn.example.com/assets/logo.png

動態設定 publicPath

您可以使用執行時程式碼中的 __webpack_public_path__ 動態設定 publicPath,而 __webpack_public_path__ 將覆蓋 Rspack 設定中的 publicPath,但它只會對動態載入的資源生效。

首先建立一個 publicPath.js

publicPath.js
__webpack_public_path__ = 'https://cdn.example.com/assets/';

然後將其匯入到入口檔案的第一行

entry.js
import './publicPath.js';
import './others.js';

output.scriptType

  • 類型: 'module' | 'text/javascript' | boolean
  • 預設值: false

此選項允許使用自訂的 script 類型載入非同步 chunks,例如 <script type="module" ...>

提示

如果 output.module 設定為 true,則 output.scriptType 將預設為 'module' 而不是 false

rspack.config.js
module.exports = {
  //...
  output: {
    scriptType: 'module',
  },
};

output.sourceMapFilename

  • 類型: string
  • 預設值: '[file].map[query]'

設定 source maps 的命名方式。只有當 devtool 設定為 'source-map' 時才會生效,這會寫入一個輸出檔案。

可以使用 output.filename 中的 [name][id][fullhash][chunkhash] 替換。除此之外,您可以使用 Template strings 中 Filename-level 下列出的替換。

output.strictModuleErrorHandling

  • 類型: boolean
  • 預設值: false

以效能為代價,依照 EcmaScript Modules 規範處理模組載入時的錯誤。

rspack.config.js
module.exports = {
  //...
  output: {
    strictModuleErrorHandling: true,
  },
};

output.strictModuleExceptionHandling

  • 類型: boolean

告訴 Rspack 如果模組在被 require 時拋出例外,則將其從模組實例快取 (require.cache) 中移除。

output.trustedTypes

  • 類型: true | string | object
  • 預設值: undefined

控制 Trusted Types 相容性。啟用時,Rspack 將偵測 Trusted Types 的支援,如果支援,則使用 Trusted Types policies 來建立其動態載入的 script URLs。當應用程式在 require-trusted-types-for 內容安全策略指令下執行時使用。

預設為停用(不相容,script URLs 為字串)。

  • 設定為 true 時,Rspack 將使用 output.uniqueName 作為 Trusted Types policy 名稱。
  • 設定為非空字串時,其值將用作 policy 名稱。
  • 設定為物件時,policy 名稱取自物件的 policyName 屬性。
rspack.config.js
module.exports = {
  //...
  output: {
    trustedTypes: {
      policyName: 'my-application#webpack',
    },
  },
};

output.uniqueName

  • 類型: string
  • 預設值: 它預設為 output.library 名稱或 context 中 package.json 的套件名稱,如果兩者都找不到,則設定為 ''

Rspack 建置的唯一名稱,以避免使用全域變數時發生多個 Rspack 執行時衝突。

output.uniqueName 將用於產生以下項目的唯一全域變數:

rspack.config.js
module.exports = {
  output: {
    uniqueName: 'my-package-xyz',
  },
};

output.wasmLoading

  • 類型: false | 'fetch', 'async-node'
  • 預設值: 'fetch'

設定載入 WebAssembly 模組的方法的選項。預設包含的方法有 'fetch'(web/webworker)、'async-node' (Node.js),但其他方法可能會由外掛程式加入。

預設值可能會受到不同 target 的影響

  • 如果 target 設定為 'web''webworker''electron-renderer''node-webkit',則預設為 'fetch'
  • 如果 target 設定為 'node''async-node''electron-main''electron-preload',則預設為 'async-node'
rspack.config.js
module.exports = {
  //...
  output: {
    wasmLoading: 'fetch',
  },
};

output.webassemblyModuleFilename

  • 類型: string
  • 預設值: '[hash].module.wasm'

指定 WebAssembly 模組的檔案名稱。它應作為 output.path 目錄中的相對路徑提供

rspack.config.js
module.exports = {
  //...
  output: {
    webassemblyModuleFilename: '[id].[hash].wasm',
  },
};

output.workerChunkLoading

  • 類型: false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import'
  • 預設值: false

新的選項 workerChunkLoading 控制 workers 的 chunk 載入。

提示

此選項的預設值取決於 target 設定。有關更多詳細資訊,請在 Rspack 預設值中搜尋 "workerChunkLoading"

rspack.config.js
module.exports = {
  //...
  output: {
    workerChunkLoading: false,
  },
};

output.workerPublicPath

  • 類型: string
  • 預設值: ""

設定 Worker 的 public path,預設為 output.publicPath 的值。只有當您的 worker scripts 與其他 scripts 位於不同的路徑時才使用此選項。

rspack.config.js
module.exports = {
  //...
  output: {
    workerPublicPath: '/workerPublicPath2/',
  },
};

output.workerWasmLoading

  • 類型: false | 'fetch-streaming' | 'fetch' | 'async-node' | string
  • 預設值: false

設定 workers 中載入 WebAssembly 模組的方法的選項,預設為 output.wasmLoading 的值。

rspack.config.js
module.exports = {
  //...
  output: {
    workerWasmLoading: 'fetch',
  },
};

output.auxiliaryComment

警告

output.libraryExport

警告

我們可能會取消對此的支援,因此建議改用與 libraryExport 具有相同功能的 output.library.export

output.libraryTarget

警告

請改用 output.library.type,因為我們未來可能會取消對 output.libraryTarget 的支援。

output.umdNamedDefine

警告

output.cssHeadDataCompression

  • 類型: boolean
  • 預設值: 開發模式為 false,生產模式為 true

Rspack 在 CSS 中加入一些中繼資料來解析 CSS 模組,此設定決定是否壓縮這些中繼資料。

例如

.local-a {
  color: blue;
}

head {
  --webpack-main: a: local-a/&\.\/ src\/index\.module\.css;
}

壓縮後 👇

.local-a {
  color: blue;
}

head {
  --webpack-main: &\.\/ srcăindexāmoduleācss;
}