顶层 output
键包含一组选项,指示 webpack 如何以及在哪里输出您的 bundle、资源以及您使用 webpack 打包或加载的任何其他内容。
string = '[hash][ext][query]'
function (pathData, assetInfo) => string
与 output.filename
相同,但用于 资源模块 (Asset Modules)。
[name]
、[file]
、[query]
、[fragment]
、[base]
和 [path]
对于从 Data URI 替换构建的资源会设置为空字符串。
boolean = true
创建按需加载的异步分块。
webpack.config.js
module.exports = {
//...
output: {
//...
asyncChunks: true,
},
};
string
object
当与 output.library
和 output.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',
},
},
};
boolean = true
指示 webpack 将 charset="utf-8"
添加到 HTML <script>
标签。
string = '[id].js'
function (pathData, assetInfo) => string
此选项决定了非初始分块文件的名称。有关可能的值,请参阅 output.filename
选项的详细信息。
请注意,这些文件名需要在运行时生成,以便发送分块请求。因此,像 [name]
和 [chunkhash]
这样的占位符需要在输出 bundle 中与 webpack 运行时一起添加从分块 ID 到占位符值的映射。这会增加大小,并且当任何分块的占位符值更改时,可能会使 bundle 失效。
默认使用 [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';
},
},
};
false
string: 'array-push' | 'commonjs' | 'module' | <any string>
分块的格式(默认包含的格式有 'array-push'
(web/WebWorker)、'commonjs'
(node.js)、'module'
(ESM),但其他格式可能由插件添加)。
webpack.config.js
module.exports = {
//...
output: {
//...
chunkFormat: 'commonjs',
},
};
number = 120000
分块请求过期前的毫秒数。此选项自 webpack 2.6.0 起受支持。
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoadTimeout: 30000,
},
};
string = 'webpackChunkwebpack'
webpack 用于加载分块的全局变量。
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoadingGlobal: 'myCustomFunc',
},
};
false
string: 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import' | <any string>
加载分块的方法(默认包含的方法有 'jsonp'
(web)、'import'
(ESM)、'importScripts'
(WebWorker)、'require'
(同步 node.js)、'async-node'
(异步 node.js),但其他方法可能由插件添加)。
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoading: 'async-node',
},
};
boolean
{ dry?: boolean, keep?: RegExp | string | ((filename: string) => boolean) }
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;
}
);
boolean = true
指示 webpack 在写入输出文件系统之前,检查要发射的文件是否已存在且内容相同。
module.exports = {
//...
output: {
compareBeforeEmit: false,
},
};
boolean = false
string: 'anonymous' | 'use-credentials'
指示 webpack 启用 跨域 加载分块。仅当 target
设置为 'web'
时生效,此时 webpack 会通过添加脚本标签使用 JSONP 加载按需分块。
'anonymous'
- 启用不带凭据的跨域加载'use-credentials'
- 启用带凭据的跨域加载string
function (pathData, assetInfo) => string
此选项决定了非初始 CSS 输出文件在磁盘上的名称。有关可能的值,请参阅 output.filename
选项的详细信息。
您不得在此处指定绝对路径。但是,您可以随意包含以 '/'
分隔的文件夹。此指定路径将与 output.path
值结合使用,以确定磁盘上的位置。
string
function (pathData, assetInfo) => string
此选项决定了 CSS 输出文件在磁盘上的名称。有关可能的值,请参阅 output.filename
选项的详细信息。
您不得在此处指定绝对路径。但是,您可以随意包含以 '/'
分隔的文件夹。此指定路径将与 output.path
值结合使用,以确定磁盘上的位置。
string
function (info)
当上述模板字符串或函数产生重复项时,将使用回退。
请参阅 output.devtoolModuleFilenameTemplate
。
string = 'webpack://[namespace]/[resource-path]?[loaders]'
function (info) => string
此选项仅在 devtool
使用需要模块名称的选项时使用。
自定义每个 Source Map 的 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.devtoolModuleFilenameTemplate
一起使用的模块命名空间。未指定时,它将默认为 output.uniqueName
的值。它用于在加载使用 webpack 构建的多个库时,防止 Source Map 中的源文件路径冲突。
例如,如果您有两个库,命名空间分别为 library1
和 library2
,它们都包含一个文件 ./src/index.js
(可能内容不同),它们将把这些文件暴露为 webpack://library1/./src/index.js
和 webpack://library2/./src/index.js
。
您可以使用像 [name]
这样的模板字符串,根据构建上下文动态生成命名空间,提供额外的灵活性。
webpack.config.js
module.exports = {
//...
output: {
filename: '[name]-bundle.js',
library: 'library-[name]',
libraryTarget: 'commonjs',
devtoolNamespace: 'library-[name]', // Sets a unique namespace for each library
},
};
[string: 'jsonp' | 'import-scripts' | 'require' | 'async-node' | <any string>]
入口点启用的分块加载类型列表。将由 webpack 自动填充。仅在使用函数作为 entry 选项并从那里返回 chunkLoading 选项时才需要。
webpack.config.js
module.exports = {
//...
output: {
//...
enabledChunkLoadingTypes: ['jsonp', 'require'],
},
};
[字符串]
入口点启用的库类型列表。
module.exports = {
//...
output: {
enabledLibraryTypes: ['module'],
},
};
[字符串]
入口点启用的 WebAssembly 加载类型列表。
module.exports = {
//...
output: {
enabledWasmLoadingTypes: ['fetch'],
},
};
告知 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 '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,
},
},
};
string
function (pathData, assetInfo) => string
此选项决定了每个输出 bundle 的名称。bundle 将写入由 output.path
选项指定的目录。
对于单个 entry
入口点,这可以是一个静态名称。
webpack.config.js
module.exports = {
//...
output: {
filename: 'bundle.js',
},
};
然而,当通过多个入口点、代码分割或各种插件创建多个 bundle 时,您应该使用以下替换之一为每个 bundle 提供唯一的名称...
使用入口名称
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'
的形式来创建文件夹结构。
模板字符串中可用的替换项如下(通过 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;
};
string = 'self'
当以库为目标时,特别是当 library.type
为 'umd'
时,此选项指示将使用哪个全局对象来挂载库。为了使 UMD 构建在浏览器和 Node.js 上都可用,请将 output.globalObject
选项设置为 'this'
。对于类似 Web 的目标,默认为 self
。
入口点的返回值将使用 output.library.name
的值分配给全局对象。根据 type
选项的值,全局对象可能会相应更改,例如 self
、global
或 globalThis
。
例如
webpack.config.js
module.exports = {
// ...
output: {
library: {
name: 'myLib',
type: 'umd',
},
filename: 'myLib.js',
globalObject: 'this',
},
};
string = 'hex'
生成哈希时使用的编码。支持 Node.JS hash.digest
中的所有编码。在文件名中使用 'base64'
可能会有问题,因为它在字母表中包含字符 /
。同样,'latin1'
可能包含任何字符。
number = 20
要使用的哈希摘要的前缀长度。
string = 'md4'
function
要使用的哈希算法。支持 Node.JS crypto.createHash
中的所有函数。自 4.0.0-alpha2
起,hashFunction
可以是自定义哈希函数的构造函数。出于性能原因,您可以提供非加密哈希函数。
module.exports = {
//...
output: {
hashFunction: require('metrohash').MetroHash64,
},
};
确保哈希函数具有可用的 update
和 digest
方法。
一个可选的盐值,用于通过 Node.JS 的 hash.update
更新哈希。
string = '[id].[fullhash].hot-update.js'
自定义热更新分块的文件名。有关可能的值,请参阅 output.filename
选项的详细信息。
这里只允许使用占位符 [id]
和 [fullhash]
,默认值为:
webpack.config.js
module.exports = {
//...
output: {
hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
},
};
字符串
仅当 target
设置为 'web'
时使用,此时 webpack 使用 JSONP 加载热更新。
使用 JSONP 函数异步加载热更新分块。
有关详细信息,请参阅 output.chunkLoadingGlobal
。
string = '[runtime].[fullhash].hot-update.json'
function
自定义主热更新文件名。[fullhash]
和 [runtime]
可用作占位符。
boolean = true
指示 webpack 在发射的代码周围添加 IIFE 包装器。
module.exports = {
//...
output: {
iife: true,
},
};
boolean = false
在生产环境中隐藏浏览器控制台的警告。此选项不影响终端/控制台输出。
webpack.config.js
module.exports = {
//...
output: {
ignoreBrowserWarnings: true,
},
};
string = 'import'
原生 import()
函数的名称。可用于 polyfill,例如与 dynamic-import-polyfill
结合使用。
webpack.config.js
module.exports = {
//...
output: {
importFunctionName: '__import__',
},
};
字符串
原生 import.meta
对象的名称(可以替换为 polyfill)。
webpack.config.js
module.exports = {
//...
output: {
importMetaName: 'pseudoImport.meta',
},
};
输出一个库,暴露您的入口点的导出。
string | string[] | object
让我们看一个示例。
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 可以接受多种入口点,例如 array
或 object
。
如果您提供一个 array
作为 entry
入口点,则只有数组中的最后一个会被暴露。
module.exports = {
// …
entry: ['./src/a.js', './src/b.js'], // only exports in b.js will be exposed
output: {
library: 'MyLibrary',
},
};
如果提供一个 object
作为 entry
入口点,所有入口都可以使用 library
的 array
语法暴露。
module.exports = {
// …
entry: {
a: './src/a.js',
b: './src/b.js',
},
output: {
filename: '[name].js',
library: ['MyLibrary', '[name]'], // name is a placeholder here
},
};
假设 a.js
和 b.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',
},
},
},
};
使用一个容器(在全局空间中定义)来调用 AMD 模块中的 define
/require
函数。
module.exports = {
// …
output: {
library: {
amdContainer: 'window["clientContainer"]',
type: 'amd', // or 'amd-require'
},
},
};
这将生成以下 bundle:
window['clientContainer'].define(/*define args*/); // or 'amd-require' window['clientContainer'].require(/*require args*/);
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
},
},
};
为库指定一个名称。
类型
string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}
配置库的暴露方式。
类型:`string`
默认包含的类型有 'var'
、'module'
、'modern-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
提供的名称。
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'var',
},
},
};
当你的库加载时,**入口点的返回值**将被分配给一个变量。
var MyLibrary = _entry_return_;
// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'assign',
},
},
};
这将生成一个隐式全局变量,它有可能重新分配现有值(请谨慎使用)
MyLibrary = _entry_return_;
请注意,如果 MyLibrary
未在此之前定义,你的库将被设置在全局作用域中。
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
定义的名称。
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
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'window',
},
},
};
**入口点的返回值**将使用 output.library.name
值分配给 window
对象。
window['MyLibrary'] = _entry_return_;
window.MyLibrary.doSomething();
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'global',
},
},
};
**入口点的返回值**将使用 output.library.name
值分配给全局对象。根据 target
值,全局对象可能会相应改变,例如 self
、global
或 globalThis
。
global['MyLibrary'] = _entry_return_;
global.MyLibrary.doSomething();
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'commonjs',
},
},
};
**入口点的返回值**将使用 output.library.name
值分配给 exports
对象。顾名思义,这用于 CommonJS 环境中。
exports['MyLibrary'] = _entry_return_;
require('MyLibrary').doSomething();
这些选项将生成一个带有完整头部(header)的捆绑包,以确保与各种模块系统兼容。在以下 output.library.type
选项下,output.library.name
选项将具有不同的含义。
module.exports = {
// …
experiments: {
outputModule: true,
},
output: {
library: {
// do not specify a `name` here
type: 'module',
},
},
};
输出 ES 模块。
然而,此功能仍处于实验阶段,尚未完全支持,因此请务必事先启用 experiments.outputModule。此外,你可以在 此线程 中跟踪开发进度。
module.exports = {
// …
experiments: {
outputModule: true,
},
output: {
library: {
// do not specify a `name` here
type: 'modern-module',
},
},
};
此配置为 ES 模块生成可进行摇树优化的输出。
然而,此功能仍处于实验阶段,尚未完全支持,因此请务必事先启用 experiments.outputModule。
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.name
与 type: commonjs2
一起指定,入口点的返回值将被分配给 module.exports.[output.library.name]
。
commonjs-module
等同于 commonjs2
。我们可能会在未来版本中移除 commonjs-module
。
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]
这将把你的库暴露为 AMD 模块。
AMD 模块要求入口块(例如,由 <script>
标签加载的第一个脚本)使用特定的属性定义,例如 define
和 require
,这些通常由 RequireJS 或任何兼容的加载器(如 almond)提供。否则,直接加载生成的 AMD 捆绑包将导致类似于 define is not defined
的错误。
使用以下配置...
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.path
和 output.filename
直接暴露在服务器上,它们可能对于此特定设置变得很重要。
module.exports = {
//...
output: {
library: {
name: 'MyLibrary',
type: 'amd-require',
},
},
};
这将用一个立即执行的 AMD require(dependencies, factory)
包装器来打包你的输出。
'amd-require'
类型允许使用 AMD 依赖项,而无需单独的后续调用。与 'amd'
类型一样,这取决于在加载 webpack 输出的环境中,是否存在适当的 require
函数。
使用此类型时,库名称无法使用。
这将把你的库暴露在所有模块定义下,使其可以与 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.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 () {
// ...
},
};
}
);
module.exports = {
// …
output: {
library: {
name: 'MyLibrary',
type: 'jsonp',
},
},
};
这将把你的入口点的返回值封装到一个 jsonp 包装器中。
MyLibrary(_entry_return_);
你的库的依赖项将由 externals
配置定义。
指定哪个导出应该作为库暴露。
string | string[]
默认情况下是 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;
在 UMD 包装器中添加注释。
string | { amd?: string, commonjs?: string, commonjs2?: string, root?: string }
要为每种 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.type: "umd"
时,将 output.library.umdNamedDefine
设置为 true
将命名 UMD 构建的 AMD 模块。否则,将使用匿名 define
。
module.exports = {
//...
output: {
library: {
name: 'MyLibrary',
type: 'umd',
umdNamedDefine: true,
},
},
};
AMD 模块将是
define('MyLibrary', [], factory);
string
[string]
配置哪些模块或模块将通过 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();
字符串 = 'var'
配置库如何暴露。可以使用以下任何选项。请注意,此选项与分配给 output.library
的值协同工作。对于以下示例,假设 output.library
的值配置为 MyLibrary
。
这些选项将入口点的返回值(即入口点导出的任何内容)分配给在捆绑包被包含的作用域中,由 output.library
提供的名称。
当你的库加载时,**入口点的返回值**将被分配给一个变量。
var MyLibrary = _entry_return_;
// In a separate script...
MyLibrary.doSomething();
这将生成一个隐式全局变量,它有可能重新分配现有值(请谨慎使用)
MyLibrary = _entry_return_;
请注意,如果 MyLibrary
未在此之前定义,你的库将被设置在全局作用域中。
如果目标对象存在,则将返回值复制到目标对象,否则首先创建目标对象。
// 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_);
**入口点的返回值**将被分配给 this,作为 output.library
命名的属性。this
的含义由你决定。
this['MyLibrary'] = _entry_return_;
// In a separate script...
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if this is window
**入口点的返回值**将使用 output.library
值分配给 window
对象。
window['MyLibrary'] = _entry_return_;
window.MyLibrary.doSomething();
**入口点的返回值**将使用 output.library
值分配给 global
对象。
global['MyLibrary'] = _entry_return_;
global.MyLibrary.doSomething();
**入口点的返回值**将使用 output.library
值分配给 exports
对象。顾名思义,这用于 CommonJS 环境中。
exports['MyLibrary'] = _entry_return_;
require('MyLibrary').doSomething();
这些选项将生成一个带有完整头部(header)的捆绑包,以确保与各种模块系统兼容。在以下 output.libraryTarget
选项下,output.library
选项将具有不同的含义。
输出 ES 模块。请务必事先启用 experiments.outputModule。
请注意,此功能尚未完全支持,请在 此线程 中跟踪进度。
**入口点的返回值**将被分配给 module.exports
。顾名思义,这用于 CommonJS 环境中。
module.exports = _entry_return_;
require('MyLibrary').doSomething();
请注意,output.library
不能与此特定的 output.libraryTarget
一起使用,有关更多详细信息,请阅读此问题。
这将把你的库暴露为 AMD 模块。
AMD 模块要求入口块(例如,由 <script>
标签加载的第一个脚本)使用特定的属性定义,例如 define
和 require
,这些通常由 RequireJS 或任何兼容的加载器(如 almond)提供。否则,直接加载生成的 AMD 捆绑包将导致类似于 define is not defined
的错误。
使用以下配置...
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.path
和 output.filename
直接暴露在服务器上,它们可能对于此特定设置变得很重要。
这将用一个立即执行的 AMD require(dependencies, factory)
包装器来打包你的输出。
'amd-require'
目标允许使用 AMD 依赖项,而无需单独的后续调用。与 'amd'
目标一样,这取决于在加载 webpack 输出的环境中,是否存在适当的 require
函数。
使用此目标时,库名称将被忽略。
这将把你的库暴露在所有模块定义下,使其可以与 CommonJS、AMD 和全局变量一起工作。查看 UMD 仓库以了解更多信息。
在这种情况下,你需要 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',
},
};
这将把你的库暴露为 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);
});
这将把你的入口点的返回值封装到一个 jsonp 包装器中。
MyLibrary(_entry_return_);
你的库的依赖项将由 externals
配置定义。
boolean = false
将 JavaScript 文件输出为模块类型。由于是实验性功能,默认禁用。
启用后,webpack 将内部设置 output.iife
为 false
,output.scriptType
为 'module'
,以及 terserOptions.module
为 true
。
如果你使用 webpack 编译供他人使用的库,请确保在 output.module
为 true
时将 output.libraryTarget
设置为 'module'
。
module.exports = {
//...
experiments: {
outputModule: true,
},
output: {
module: true,
},
};
字符串 = path.join(process.cwd(), 'dist')
作为**绝对**路径的输出目录。
webpack.config.js
const path = require('path');
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'dist/assets'),
},
};
请注意,此参数中的 [fullhash]
将替换为编译的哈希值。有关详细信息,请参阅缓存指南。
boolean=true
string: 'verbose'
告诉 webpack 在捆绑包中包含有关所含模块的信息注释。此选项在 development
mode 中默认为 true
,在 production
mode 中默认为 false
。'verbose'
显示更多信息,如导出、运行时要求和提前退出。
webpack.config.js
module.exports = {
//...
output: {
pathinfo: true,
},
};
类型
函数
字符串
对于 web
和 web-worker
目标,output.publicPath
默认为 'auto'
,请参阅此指南以了解其用例。
当使用按需加载或加载外部资源(如图像、文件等)时,这是一个重要的选项。如果指定了不正确的值,你将在加载这些资源时收到 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',
},
};
对 chunk 的请求将类似于 /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__
的更多信息,请参阅此讨论。
string: 'module' | 'text/javascript'
boolean = false
此选项允许使用自定义脚本类型加载异步 chunks,例如 <script type="module" ...>
。
module.exports = {
//...
output: {
scriptType: 'module',
},
};
字符串 = '[file].map[query]'
配置源映射的命名方式。仅当 devtool
设置为 'source-map'
时生效,后者会写入输出文件。
可以使用 output.filename
中的 [name]
、[id]
、[fullhash]
和 [chunkhash]
替换。除此之外,你还可以使用模板字符串中“文件名级别”下列出的替换。
字符串 = ''
更改输出捆绑包中每行的前缀。
webpack.config.js
module.exports = {
//...
output: {
sourcePrefix: '\t',
},
};
以性能为代价,按照 EcmaScript 模块规范处理模块加载中的错误。
boolean
module.exports = {
//...
output: {
strictModuleErrorHandling: true,
},
};
boolean = 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
true
string
object
控制 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',
},
},
};
字符串 = 'stop': 'continue' | 'stop'
判断是继续加载,预期 require-trusted-types-for 'script'
未被强制执行,还是在调用 trustedTypes.createPolicy(...)
失败时(因为策略名称不在 CSP 的 trusted-types
列表中或重复)立即失败。
module.exports = {
//...
output: {
//...
trustedTypes: {
policyName: 'my-application#webpack',
onPolicyCreationFailure: 'continue',
},
},
};
布尔值
当使用 libraryTarget: "umd"
时,将 output.umdNamedDefine
设置为 true
会命名 UMD 构建的 AMD 模块。否则会使用匿名的 define
。
module.exports = {
//...
output: {
umdNamedDefine: true,
},
};
字符串
Webpack 构建的唯一名称,以避免在使用全局变量时,多个 webpack 运行时发生冲突。它默认为 output.library
名称或上下文中 package.json
中的包名,如果两者都未找到,则设置为空字符串 ''
。
output.uniqueName
将用于为以下项生成唯一的全局变量:
webpack.config.js
module.exports = {
// ...
output: {
uniqueName: 'my-package-xyz',
},
};
false
'fetch' | 'async-node'
string
设置加载 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'
。module.exports = {
//...
output: {
wasmLoading: 'fetch',
},
};
string = '[hash].module.wasm'
指定 WebAssembly 模块的文件名。它应作为 output.path
目录内的相对路径提供。
module.exports = {
//...
output: {
webassemblyModuleFilename: '[id].[hash].wasm',
},
};
string: 'require' | 'import-scripts' | 'async-node' | 'import' | 'universal'
boolean: false
新选项 workerChunkLoading
控制 worker 的分块加载。
webpack.config.js
module.exports = {
//...
output: {
workerChunkLoading: false,
},
};
字符串
为 Worker 设置公共路径,默认为 output.publicPath 的值。仅当您的 worker 脚本与您的其他脚本位于不同路径时才使用此选项。
webpack.config.js
module.exports = {
//...
output: {
workerPublicPath: '/workerPublicPath2/',
},
};
false
'fetch-streaming' | 'fetch' | 'async-node'
string
设置在 worker 中加载 WebAssembly 模块的方法选项,默认为 output.wasmLoading 的值。
webpack.config.js
module.exports = {
//...
output: {
workerWasmLoading: 'fetch',
},
};