輸出

頂層的 output 鍵包含一組選項,指示 webpack 如何以及在哪裡輸出您的套件、資產,以及您使用 webpack 套件或載入的其他任何內容。

output.assetModuleFilename

字串 = '[hash][ext][query]' 函式 (pathData, assetInfo) => 字串

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

[name][file][query][fragment][base][path] 會設定為從資料 URI 替換建置的資產的空字串。

output.asyncChunks

布林值 = true

建立依需求載入的非同步區塊。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    asyncChunks: true,
  },
};

output.auxiliaryComment

字串 物件

output.libraryoutput.libraryTarget 搭配使用時,此選項允許使用者在匯出包裝中插入註解。若要為每個 libraryTarget 類型插入相同的註解,請將 auxiliaryComment 設定為字串

webpack.config.js

module.exports = {
  //...
  output: {
    library: 'someLibName',
    libraryTarget: 'umd',
    filename: 'someLibName.js',
    auxiliaryComment: 'Test Comment',
  },
};

將會產生以下結果

someLibName.js

(function webpackUniversalModuleDefinition(root, factory) {
  // Test Comment
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory(require('lodash'));
  // Test Comment
  else if (typeof define === 'function' && define.amd)
    define(['lodash'], factory);
  // Test Comment
  else if (typeof exports === 'object')
    exports['someLibName'] = factory(require('lodash'));
  // Test Comment
  else root['someLibName'] = factory(root['_']);
})(this, function (__WEBPACK_EXTERNAL_MODULE_1__) {
  // ...
});

若要精細控制每個 libraryTarget 註解,請傳遞物件

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    auxiliaryComment: {
      root: 'Root Comment',
      commonjs: 'CommonJS Comment',
      commonjs2: 'CommonJS2 Comment',
      amd: 'AMD Comment',
    },
  },
};

output.charset

布林值 = true

告訴 webpack 將 charset="utf-8" 加入 HTML <script> 標籤。

output.chunkFilename

字串 = '[id].js' 函式 (pathData, assetInfo) => 字串

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

請注意,這些檔案名稱需要在執行階段產生,以傳送區塊請求。因此,像 [name][chunkhash] 這樣的佔位符需要將區塊 ID 對應到佔位符值,並將 webpack 執行階段的輸出套件。這會增加大小,並可能在任何區塊的佔位符值變更時使套件失效。

預設使用 [id].js 或從 output.filename 推斷的值([name] 會替換為 [id] 或在前面加上 [id].)。

webpack.config.js

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

作為函式使用

webpack.config.js

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

output.chunkFormat

false 字串:'array-push' | 'commonjs' | 'module' | <任何字串>

區塊的格式(預設包含的格式為 'array-push'(網頁/WebWorker)、'commonjs'(node.js)、'module'(ESM),但外掛程式可能會加入其他格式)。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    chunkFormat: 'commonjs',
  },
};

output.chunkLoadTimeout

數字 = 120000

區塊請求逾時前的毫秒數。此選項自 webpack 2.6.0 起支援。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    chunkLoadTimeout: 30000,
  },
};

output.chunkLoadingGlobal

字串 = 'webpackChunkwebpack'

webpack 使用此全域變數來載入區塊。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    chunkLoadingGlobal: 'myCustomFunc',
  },
};

output.chunkLoading

false 字串:'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import' | <任何字串>

載入區塊的方法(預設包含的方法為 'jsonp'(網頁)、'import'(ESM)、'importScripts'(WebWorker)、'require'(同步 node.js)、'async-node'(非同步 node.js),但外掛程式可能會加入其他方法)。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    chunkLoading: 'async-node',
  },
};

output.clean

5.20.0+

布林值 { dry?: 布林值, keep?: RegExp | 字串 | ((filename: 字串) => 布林值) }

module.exports = {
  //...
  output: {
    clean: true, // Clean the output directory before emit.
  },
};
module.exports = {
  //...
  output: {
    clean: {
      dry: true, // Log the assets that should be removed instead of deleting them.
    },
  },
};
module.exports = {
  //...
  output: {
    clean: {
      keep: /ignored\/dir\//, // Keep these assets under 'ignored/dir'.
    },
  },
};

// or

module.exports = {
  //...
  output: {
    clean: {
      keep(asset) {
        return asset.includes('ignored/dir');
      },
    },
  },
};

您也可以搭配 hook 使用

webpack.CleanPlugin.getCompilationHooks(compilation).keep.tap(
  'Test',
  (asset) => {
    if (/ignored\/dir\//.test(asset)) return true;
  }
);

output.compareBeforeEmit

布林值 = true

指示 webpack 在寫入輸出檔案系統之前,檢查要發射的檔案是否已存在且具有相同的內容。

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

output.crossOriginLoading

boolean = false 字串: 'anonymous' | 'use-credentials'

指示 webpack 啟用區塊的 跨來源 載入。僅在 target 設定為 'web' 時生效,它會透過加入 script 標籤,使用 JSONP 載入依需求區塊。

  • 'anonymous' - 啟用跨來源載入不含憑證
  • 'use-credentials' - 啟用跨來源載入含憑證

output.cssChunkFilename

字串 函式 (pathData, assetInfo) => 字串

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

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

output.cssFilename

字串 函式 (pathData, assetInfo) => 字串

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

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

output.cssHeadDataCompression

5.91.0+

布林值

此選項決定是否壓縮在 CSS 檔案的 head 標籤中產生的元資料。此選項在 production 中預設為 true,在 development 模式 中預設為 false

output.devtoolFallbackModuleFilenameTemplate

字串 函式 (info)

當以上的範本字串或函式產生重複時,會使用備用選項。

請參閱 output.devtoolModuleFilenameTemplate

output.devtoolModuleFilenameTemplate

字串 = 'webpack://[命名空間]/[資源路徑]?[載入程式]' 函式 (info) => 字串

此選項僅在 devtool 使用需要模組名稱的選項時使用。

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

webpack.config.js

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

範本字串中提供以下替換 (透過 webpack 內部的 ModuleFilenameHelpers)。

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

當使用函式時,相同的選項會透過 info 參數以駝峰式命名方式提供。

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

如果多個模組會產生相同的名稱,則會使用 output.devtoolFallbackModuleFilenameTemplate 來代替這些模組。

output.devtoolNamespace

字串

此選項決定與 output.devtoolModuleFilenameTemplate 一起使用的模組命名空間。未指定時,它會預設為 output.uniqueName 的值。它用於防止在載入使用 webpack 建置的多個函式庫時,原始碼檔案路徑在原始碼對應表中發生衝突。

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

output.enabledChunkLoadingTypes

[字串:'jsonp' | 'import-scripts' | 'require' | 'async-node' | <任何字串>]

可供進入點使用的區塊載入類型清單。Webpack 會自動填入。僅在使用函式作為進入點選項並從中傳回區塊載入選項時需要。

webpack.config.js

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

output.enabledLibraryTypes

[字串]

可供進入點使用的函式庫類型清單。

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

output.enabledWasmLoadingTypes

[字串]

可供進入點使用的 wasm 載入類型清單。

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

output.environment

告訴 webpack 在產生的執行時期程式碼中可以使用哪種類型的 ES 功能。

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 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,
      // The environment supports optional chaining ('obj?.a' or 'obj?.()').
      optionalChaining: true,
      // The environment supports template literals.
      templateLiteral: true,
    },
  },
};

output.filename

字串 函式 (pathData, assetInfo) => 字串

此選項決定每個輸出套件的名稱。套件會寫入由 output.path 選項指定的目錄。

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

webpack.config.js

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

但是,透過多個進入點、程式碼拆分或各種外掛程式建立多個套件時,您應該使用下列其中一種替換,讓每個套件都有獨特的名稱...

使用進入點名稱

webpack.config.js

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

使用內部區塊 ID

webpack.config.js

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

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

webpack.config.js

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

結合多個替換

webpack.config.js

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

使用函式傳回檔名

webpack.config.js

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

請務必閱讀 快取指南 以取得詳細資訊。除了設定此選項外,還有更多步驟。

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

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

範本字串

範本字串中可使用下列替換(透過 webpack 內部的 TemplatedPathPlugin

編譯層級可用的替換

範本說明
[fullhash]編譯的完整雜湊
[hash]相同,但已棄用

區塊層級可用的替換

範本說明
[id]區塊的 ID
[name]區塊的名稱(如果已設定),否則為區塊的 ID
[chunkhash]區塊的雜湊,包括區塊的所有元素
[contenthash]區塊的雜湊,僅包括此內容類型的元素(受 optimization.realContentHash 影響)

模組層級可用的替換

範本說明
[id]模組的 ID
[moduleid]相同,但已棄用
[hash]模組的雜湊
[modulehash]相同,但已棄用
[contenthash]模組內容的雜湊

檔案層級可用的替換

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

URL 層級可用的替換

範本說明
[url]URL

雜湊長度([hash][contenthash][chunkhash])可以使用 [hash:16] 指定(預設為 20)。或者,指定 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

字串 = 'self'

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

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

例如

webpack.config.js

module.exports = {
  // ...
  output: {
    library: {
      name: 'myLib',
      type: 'umd',
    },
    filename: 'myLib.js',
    globalObject: 'this',
  },
};

output.hashDigest

字串 = 'hex'

產生雜湊時要使用的編碼。支援 Node.JS 的 hash.digest 中的所有編碼。由於 'base64' 的字母表中包含字元 /,因此將其用於檔名可能會出現問題。同樣地,'latin1' 可能包含任何字元。

output.hashDigestLength

數字 = 20

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

output.hashFunction

字串 = 'md4' 函式

要使用的雜湊演算法。支援 Node.JS 的 crypto.createHash 中的所有函式。自 4.0.0-alpha2 起,hashFunction 現在可以是自訂雜湊函式的建構函式。您可以提供非加密雜湊函式以提升效能。

module.exports = {
  //...
  output: {
    hashFunction: require('metrohash').MetroHash64,
  },
};

請確定雜湊函式會有 updatedigest 方法可用。

output.hashSalt

一個可選的 salt,用於透過 Node.JS 的 hash.update 來更新雜湊。

output.hotUpdateChunkFilename

字串 = '[id].[fullhash].hot-update.js'

自訂熱更新區塊的檔名。有關可能值の詳細資訊,請參閱 output.filename 選項。

在此允許的唯一佔位符為 [id][fullhash],預設為

webpack.config.js

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

output.hotUpdateGlobal

字串

僅在將 target 設定為 'web' 時使用,其使用 JSONP 來載入熱更新。

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

有關詳細資訊,請參閱 output.chunkLoadingGlobal

output.hotUpdateMainFilename

字串 = '[runtime].[fullhash].hot-update.json' 函式

自訂主要的熱更新檔名。[fullhash][runtime] 可用作佔位符。

output.iife

布林值 = true

指示 webpack 在發出的程式碼周圍新增 IIFE 包裹器。

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

output.ignoreBrowserWarnings

5.81.0+

布林值 = false

在生產環境中隱藏瀏覽器主控台的警告。此選項不會影響終端機/主控台輸出。

webpack.config.js

module.exports = {
  //...
  output: {
    ignoreBrowserWarnings: true,
  },
};

output.importFunctionName

字串 = 'import'

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

webpack.config.js

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

output.importMetaName

字串

原生 import.meta 物件的名稱(可交換為多重填補)。

webpack.config.js

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

output.library

輸出一個公開您進入點匯出的函式庫。

  • 類型:字串 | 字串陣列 | 物件

讓我們來看一個範例。

webpack.config.js

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

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

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

現在變數 MyLibrary 將會繫結到您進入檔的匯出,以下是使用 webpack 捆綁函式庫的方式

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

在上述範例中,我們將單一進入檔傳遞給 entry,然而,webpack 可以接受 多種進入點,例如:陣列物件

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

    module.exports = {
      // …
      entry: ['./src/a.js', './src/b.js'], // only exports in b.js will be exposed
      output: {
        library: 'MyLibrary',
      },
    };
  2. 如果提供一個 物件 作為 entry 點,所有進入點都可以使用 library陣列 語法公開。

    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('webpack');
      MyLibrary.b.hello('webpack');
    </script>

    請參閱 此範例 以了解更多資訊。

    請注意,如果您要針對每個進入點設定函式庫選項,上述設定將無法如預期般運作。以下是 在每個進入點下 執行的步驟

    module.exports = {
      // …
      entry: {
        main: {
          import: './src/index.js',
          library: {
            // all options under `output.library` can be used here
            name: 'MyLibrary',
            type: 'umd',
            umdNamedDefine: true,
          },
        },
        another: {
          import: './src/another.js',
          library: {
            name: 'AnotherLibrary',
            type: 'commonjs2',
          },
        },
      },
    };

output.library.amdContainer

5.78.0+

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

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

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

指定函式庫的名稱。

  • 類型

    string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}

output.library.type

設定函式庫公開的方式。

  • 類型:字串

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

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

公開變數

這些選項會將進入點的回傳值(例如進入點匯出的任何內容)指定給 output.library.name 提供的名稱,範圍為捆綁所包含的任何範圍。

類型:'var'
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'
5.16.0+
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.namethis 的意義由您決定

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.type 選項下將具有不同的意義。

類型:'module'
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();

如果我們指定 output.library.nametype: commmonjs2,輸入點的回傳值將會指定給 module.exports.[output.library.name]

type: 'commonjs-static'
5.66.0+
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]
type: 'amd'

這會將您的函式庫公開為 AMD 模組。

AMD 模組要求輸入區塊(例如由 <script> 標籤載入的第一個指令碼)定義為特定屬性,例如 definerequire,這通常由 RequireJS 或任何相容的載入器(例如 almond)提供。否則,直接載入產生的 AMD 程式集將會導致錯誤,例如 define 未定義

使用下列設定...

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'
module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd-require',
    },
  },
};

此功能會將您的輸出封裝在立即執行的 AMD require(dependencies, factory) 包裝函式中。

'amd-require' 類型允許使用 AMD 相依項,而無需後續的個別呼叫。與 'amd' 類型一樣,這取決於在載入 webpack 輸出的環境中,是否有適當的 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: {
    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 {
    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 模組。此功能最初在 webpack 4.30.0 中發布。

System 模組要求在執行 webpack 組合時,瀏覽器中存在全域變數 System。編譯成 System.register 格式可讓您在沒有其他組態的情況下執行 System.import('/bundle.js'),並將您的 webpack 組合載入 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'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'jsonp',
    },
  },
};

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

MyLibrary(_entry_return_);

您的函式庫的依賴項將由 externals 設定檔定義。

output.library.export

指定應公開為函式庫的輸出。

  • 類型:字串 | 字串陣列

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

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

您的進入點的預設輸出將指定給函式庫名稱

// if your entry has a default export
var MyLibrary = _entry_return_.default;

您也可以將陣列傳遞給 output.library.export,它將被解釋為要指定給函式庫名稱的模組路徑

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

以下是函式庫程式碼

var MyLibrary = _entry_return_.default.subModule;

output.library.auxiliaryComment

在 UMD 包裝器中加入註解。

  • 類型:字串 | { amd?: 字串, commonjs?: 字串, commonjs2?: 字串, root?: 字串 }

若要為每個 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

布林值

使用 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.libraryExport

字串 [字串]

設定將透過 libraryTarget 公開哪個模組或模組。預設為 undefined,如果您將 libraryTarget 設定為空字串 (例如 ''),將套用相同的行為,它會輸出整個 (命名空間) 物件。以下範例說明使用 libraryTarget: 'var' 時,此設定的影響。

支援下列設定

libraryExport: 'default' - 進入點的預設輸出將會指派給函式庫目標

// if your entry has a default export of `MyDefaultModule`
var MyDefaultModule = _entry_return_.default;

libraryExport: 'MyModule' - 指定的模組將會指派給函式庫目標

var MyModule = _entry_return_.MyModule;

libraryExport: ['MyModule', 'MySubModule'] - 陣列會被解譯為模組的路徑,並指派給函式庫目標

var MySubModule = _entry_return_.MyModule.MySubModule;

在指定了上述 libraryExport 組態後,產生的函式庫可以用以下方式使用

MyDefaultModule.doSomething();
MyModule.doSomething();
MySubModule.doSomething();

output.libraryTarget

字串 = 'var'

設定函式庫的公開方式。可以使用下列任一選項。請注意,此選項會與指派給 output.library 的值搭配使用。在以下範例中,假設 output.library 的值已設定為 MyLibrary

公開變數

這些選項會將進入點的傳回值(例如進入點輸出的任何值)指派給 output.library 提供的名稱,範圍為套件包含的位置。

libraryTarget: 'var'

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

var MyLibrary = _entry_return_;

// In a separate script...
MyLibrary.doSomething();

libraryTarget: 'assign'

這將產生一個隱含的全局變數,它有可能重新指定現有值(請小心使用)

MyLibrary = _entry_return_;

請注意,如果 MyLibrary 沒有先定義,函式庫將會設定在全域範圍。

libraryTarget: 'assign-properties'

5.16.0+

如果目標物件存在,就將傳回值複製到該物件,否則先建立目標物件

// create the target object 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 running MyLibrary
// you can run `hello` function like so
MyLibrary.hello('World');

透過物件指派公開

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

如果 output.library 未指派為非空字串,預設行為是進入點回傳的所有屬性都會透過下列程式碼片段指派給物件,如特定 output.libraryTarget 所定義

(function (e, a) {
  for (var i in a) {
    e[i] = a[i];
  }
})(output.libraryTarget, _entry_return_);

libraryTarget: 'this'

進入點的回傳值會指派給 output.library 指定名稱的屬性下的 thisthis 的意義由您決定

this['MyLibrary'] = _entry_return_;

// In a separate script...
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if this is window

libraryTarget: 'window'

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

window['MyLibrary'] = _entry_return_;

window.MyLibrary.doSomething();

libraryTarget: 'global'

進入點的回傳值會使用 output.library 值指派給 global 物件。

global['MyLibrary'] = _entry_return_;

global.MyLibrary.doSomething();

libraryTarget: 'commonjs'

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

exports['MyLibrary'] = _entry_return_;

require('MyLibrary').doSomething();

模組定義系統

這些選項會產生一個附帶完整標頭的套件,以確保與各種模組系統相容。output.library 選項會在下列 output.libraryTarget 選項下具有不同的意義。

libraryTarget: 'module'

輸出 ES 模組。請務必事先啟用 experiments.outputModule

請注意,此功能尚未完全支援,請追蹤 此討論串 的進度。

libraryTarget: 'commonjs2'

您的進入點回傳值將會指定給 module.exports。顧名思義,這用於 CommonJS 環境

module.exports = _entry_return_;

require('MyLibrary').doSomething();

請注意,output.library 無法與此特定的 output.libraryTarget 搭配使用,如需進一步詳細資訊,請 閱讀此議題

libraryTarget: 'amd'

這會將您的函式庫公開為 AMD 模組。

AMD 模組要求輸入區塊(例如由 <script> 標籤載入的第一個指令碼)定義為特定屬性,例如 definerequire,這通常由 RequireJS 或任何相容的載入器(例如 almond)提供。否則,直接載入產生的 AMD 程式集將會導致錯誤,例如 define 未定義

使用下列設定...

module.exports = {
  //...
  output: {
    library: 'MyLibrary',
    libraryTarget: 'amd',
  },
};

產生的輸出將以「MyLibrary」為名稱進行定義,亦即

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

程式集可以包含在指令碼標籤中,而程式集可以像這樣呼叫

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

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

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

如果直接使用 <script> 標籤載入此組合,則它將無法如預期般運作,或根本無法運作(在 almond 載入器的情況下)。它只能透過相容於 RequireJS 的非同步模組載入器,使用該檔案的實際路徑來運作,因此,如果這些路徑直接在伺服器上公開,則在此特定設定中,output.pathoutput.filename 可能會變得重要。

libraryTarget: 'amd-require'

此功能會將您的輸出封裝在立即執行的 AMD require(dependencies, factory) 包裝函式中。

'amd-require' 目標允許使用 AMD 相依項,而不需要後續的個別呼叫。與 'amd' 目標一樣,這取決於在載入 webpack 輸出的環境中是否可以使用適當的 require 函式

使用此目標時,將忽略函式庫名稱。

libraryTarget: 'umd'

這會在所有模組定義中公開您的函式庫,讓它可以與 CommonJS、AMD 和全域變數搭配使用。請參閱 UMD Repository 以進一步了解。

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

module.exports = {
  //...
  output: {
    library: 'MyLibrary',
    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 if (typeof exports === 'object') exports['MyLibrary'] = factory();
  else root['MyLibrary'] = factory();
})(typeof self !== 'undefined' ? self : this, function () {
  return _entry_return_;
});

請注意,省略 library 將導致進入點回傳的所有屬性直接指定給根物件,如 物件指定區段 所述。範例

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];
  }
})(typeof self !== 'undefined' ? self : this, function () {
  return _entry_return_;
});

自 webpack 3.1.0 起,您可以為 library 指定物件,以針對不同的目標使用不同的名稱

module.exports = {
  //...
  output: {
    library: {
      root: 'MyLibrary',
      amd: 'my-library',
      commonjs: 'my-common-library',
    },
    libraryTarget: 'umd',
  },
};

libraryTarget: 'system'

這會將您的函式庫公開為 System.register 模組。此功能最初在 webpack 4.30.0 中發布。

System 模組要求在執行 webpack 組合時,瀏覽器中存在全域變數 System。編譯成 System.register 格式可讓您在沒有其他組態的情況下執行 System.import('/bundle.js'),並將您的 webpack 組合載入 System 模組註冊表中。

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

輸出

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

除了將 output.libraryTarget 設為 system 之外,再將 output.library 加入組態,輸出套件將會將套件名稱作為 System.register 的引數

System.register('my-library', [], function (_export) {
  return {
    setters: [],
    execute: function () {
      // ...
    },
  };
});

您可以透過 __system_context__ 來存取 SystemJS 內容

// Log the URL of the current SystemJS module
console.log(__system_context__.meta.url);

// Import a SystemJS module, with the current SystemJS module's url as the parentUrl
__system_context__.import('./other-file.js').then((m) => {
  console.log(m);
});

其他目標

libraryTarget: 'jsonp'

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

MyLibrary(_entry_return_);

您的函式庫的依賴項將由 externals 設定檔定義。

output.module

布林值 = false

輸出 JavaScript 檔案為模組類型。預設停用,因為這是一個實驗性功能。

啟用時,webpack 會在內部將 output.iife 設為 falseoutput.scriptType 設為 'module',以及 terserOptions.module 設為 true

如果您使用 webpack 編譯一個供其他人使用的函式庫,請務必在 output.moduletrue 時,將 output.libraryTarget 設為 'module'

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

output.path

字串 = path.join(process.cwd(), 'dist')

輸出目錄作為一個絕對路徑。

webpack.config.js

const path = require('path');

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

請注意,此參數中的 [fullhash] 將會被編譯的雜湊取代。詳情請參閱 快取指南

output.pathinfo

布林值=true 字串: 'verbose'

指示 webpack 在套件中包含有關所包含模組的資訊的註解。此選項在 模式 中的 development 預設為 true,在 production 中預設為 false'verbose' 會顯示更多資訊,例如匯出、執行時間需求和退出。

webpack.config.js

module.exports = {
  //...
  output: {
    pathinfo: true,
  },
};

output.publicPath

  • 類型

    • function

    • 字串

      output.publicPath 預設為 'auto',目標為 webweb-worker,請參閱 本指南 以了解其使用案例。

在使用依需求載入或載入外部資源(例如圖片、檔案等)時,這是個重要的選項。如果指定不正確的值,載入這些資源時會收到 404 錯誤。

這個選項指定瀏覽器參照時,輸出目錄的公開 URL。相對 URL 是相對於 HTML 頁面(或 <base> 標籤)解析的。伺服器相對 URL、協定相對 URL 或絕對 URL 也是可能的,有時也是必要的,例如在 CDN 上託管資產時。

這個選項的值會加上執行時期或載入器建立的每個 URL 的開頭。因此,這個選項的值在大部分情況下會以 / 結尾

要考慮的規則:從 HTML 頁面的觀點來看,你的 output.path 的 URL。

webpack.config.js

const path = require('path');

module.exports = {
  //...
  output: {
    path: path.resolve(__dirname, 'public/assets'),
    publicPath: 'https://cdn.example.com/assets/',
  },
};

對於這個組態

webpack.config.js

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

對區塊的請求看起來會像 /assets/4.chunk.js

輸出 HTML 的載入器可能會發出類似這樣的內容

<link href="/assets/spinner.gif" />

或在 CSS 中載入圖片時

background-image: url(/assets/spinner.gif);

webpack-dev-server 也會從 publicPath 取得提示,用來決定從哪裡提供輸出檔案。

請注意,這個參數中的 [fullhash] 會被編譯的雜湊取代。請參閱 快取指南 以取得詳細資訊。

範例

module.exports = {
  //...
  output: {
    // One of the below
    publicPath: 'auto', // It automatically determines the public path from either `import.meta.url`, `document.currentScript`, `<script />` or `self.location`.
    publicPath: 'https://cdn.example.com/assets/', // CDN (always HTTPS)
    publicPath: '//cdn.example.com/assets/', // CDN (same protocol)
    publicPath: '/assets/', // server-relative
    publicPath: 'assets/', // relative to HTML page
    publicPath: '../assets/', // relative to HTML page
    publicPath: '', // relative to HTML page (same directory)
  },
};

在輸出檔案的 publicPath 無法在編譯時得知的情況下,可以在輸入檔案中使用 自由變數 __webpack_public_path__ 將其留空,並在執行時期動態設定。

__webpack_public_path__ = myRuntimePublicPath;

// rest of your application entry

請參閱 這篇討論 以取得有關 __webpack_public_path__ 的更多資訊。

output.scriptType

字串:'module' | 'text/javascript' 布林值 = false

此選項允許使用自訂指令碼類型載入非同步區塊,例如 <script type="module" ...>

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

output.sourceMapFilename

字串 = '[file].map[query]'

設定原始碼對應檔的命名方式。僅在 devtool 設為 'source-map'(會寫入輸出檔案)時才會生效。

可以使用 output.filename 中的 [name][id][fullhash][chunkhash] 代換。此外,您還可以使用 範本字串 中檔案層級下所列的代換。

output.sourcePrefix

字串 = ''

變更輸出套件中每行的字首。

webpack.config.js

module.exports = {
  //...
  output: {
    sourcePrefix: '\t',
  },
};

output.strictModuleErrorHandling

以符合 EcmaScript 模組規範的方式處理模組載入錯誤,但會犧牲效能。

  • 類型:布林值
  • 可用:5.25.0+
module.exports = {
  //...
  output: {
    strictModuleErrorHandling: true,
  },
};

output.strictModuleExceptionHandling

布林值 = false

指示 webpack 在模組被 require 時擲回例外時,將模組從模組實例快取 (require.cache) 中移除。

它預設為 false 以提升效能。

設為 false 時,模組不會從快取中移除,這會導致例外只會在第一次 require 呼叫時擲回 (與 node.js 不相容)。

例如,考慮 module.js

throw new Error('error');

strictModuleExceptionHandling 設為 false 時,只有第一次 require 會擲回例外

// with strictModuleExceptionHandling = false
require('module'); // <- throws
require('module'); // <- doesn't throw

相反地,將 strictModuleExceptionHandling 設為 true 時,此模組的所有 require 都會擲回例外

// with strictModuleExceptionHandling = true
require('module'); // <- throws
require('module'); // <- also throws

output.trustedTypes

true 字串 物件

5.37.0+

控制 Trusted Types 相容性。啟用後,webpack 會偵測 Trusted Types 支援,如果支援,則會使用 Trusted Types 政策來建立動態載入的腳本 URL。在應用程式執行於 require-trusted-types-for 內容安全政策指令下時使用。

預設為停用(無相容性,腳本 URL 為字串)。

  • 設為 true 時,webpack 會使用 output.uniqueName 作為 Trusted Types 政策名稱。
  • 設為非空白字串時,其值會用作政策名稱。
  • 設為物件時,政策名稱會從物件的 policyName 屬性取得。

webpack.config.js

module.exports = {
  //...
  output: {
    //...
    trustedTypes: {
      policyName: 'my-application#webpack',
    },
  },
};

output.trustedTypes.onPolicyCreationFailure

字串 = 'stop': 'continue' | 'stop'

5.82.0+

決定是否繼續載入,預期 require-trusted-types-for 'script' 尚未強制執行,或是在呼叫 trustedTypes.createPolicy(...) 失敗時立即失敗,原因是政策名稱不存在於 CSP trusted-types 清單中或為重複名稱。

module.exports = {
  //...
  output: {
    //...
    trustedTypes: {
      policyName: 'my-application#webpack',
      onPolicyCreationFailure: 'continue',
    },
  },
};

output.umdNamedDefine

布林值

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

module.exports = {
  //...
  output: {
    umdNamedDefine: true,
  },
};

output.uniqueName

字串

webpack 建置的唯一名稱,可避免使用全域變數時有多個 webpack 執行時期衝突。預設為 output.library 名稱或情境中 package.json 的套件名稱,如果兩者都找不到,則設為 ''

output.uniqueName 會用於為下列項目產生唯一的全域變數

webpack.config.js

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

output.wasmLoading

false 'fetch-streaming' | 'fetch' | 'async-node' 字串

設定載入 WebAssembly 模組的方法的選項。預設包含的方法為 'fetch'(網路/WebWorker)、'async-node'(Node.js),但外掛程式可能會新增其他方法。

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

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

output.webassemblyModuleFilename

字串 = '[hash].module.wasm'

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

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

output.workerChunkLoading

字串: 'require' | 'import-scripts' | 'async-node' | 'import' | 'universal' 布林值: false

新的選項 workerChunkLoading 控制工作人員的區塊載入。

webpack.config.js

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

output.workerPublicPath

字串

設定工作人員的公開路徑,預設為 output.publicPath 的值。僅在工作人員腳本位於與其他腳本不同的路徑時使用此選項。

webpack.config.js

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

output.workerWasmLoading

false 'fetch-streaming' | 'fetch' | 'async-node' 字串

設定在工作人員中載入 WebAssembly 模組的方法的選項,預設為 output.wasmLoading 的值。

webpack.config.js

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

29 位貢獻者

sokraskipjacktomasAlabesmattceirthfvgsdhurlburtusaMagicDuckfadysamirsadekbyzykmadhavarshneyharshwardhansingheemeliEugeneHlushkog-planesmelukovNeob91anikethsahajamesgeorge007hiroppychenxsansnitin315QC-LanshumanvmrzalyaulJakobJingleheimerlong76ahabhgktanyabouman