externals
配置选项提供了一种从输出包中排除依赖项的方法。相反,创建的包依赖于消费者(任何最终用户应用程序)环境中存在的依赖项。此功能通常对库开发人员最有用,但它有各种应用。
字符串
对象
函数
RegExp
[字符串,对象,函数,RegExp]
防止捆绑某些导入的包,而是在运行时检索这些外部依赖项。
例如,从 CDN 中包含 jQuery,而不是将其捆绑
index.html
<script
src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous"
></script>
webpack.config.js
module.exports = {
//...
externals: {
jquery: 'jQuery',
},
};
这将使任何依赖模块保持不变,即下面显示的代码仍然有效
import $ from 'jquery';
$('.my-element').animate(/* ... */);
在上述 webpack.config.js
中 externals
下指定的属性名称 jquery
指示应从捆绑中排除 import $ from 'jquery'
中的模块 jquery
。为了替换此模块,将使用值 jQuery
来检索全局 jQuery
变量,因为默认外部库类型是 var
,请参阅 externalsType。
虽然我们在上面展示了一个使用外部全局变量的示例,但外部实际上可以采用以下任何一种形式:全局变量、CommonJS、AMD、ES2015 模块,请参阅 externalsType 中的更多信息。
根据 externalsType,这可能是全局变量的名称(请参阅 'global'
、'this'
、'var'
、'window'
)或模块的名称(请参阅 amd
、commonjs
、module
、umd
)。
如果您只定义一个外部,您还可以使用快捷语法
module.exports = {
//...
externals: 'jquery',
};
等于
module.exports = {
//...
externals: {
jquery: 'jquery',
},
};
您可以使用 ${externalsType} ${libraryName}
语法为外部指定 外部库类型。它将覆盖 externalsType 选项中指定的默认外部库类型。
例如,如果外部库是 CommonJS 模块,您可以指定
module.exports = {
//...
externals: {
jquery: 'commonjs jquery',
},
};
module.exports = {
//...
externals: {
subtract: ['./math', 'subtract'],
},
};
subtract: ['./math', 'subtract']
允许您选择模块的一部分,其中 ./math
是模块,而您的包仅需要 subtract
变量下的子集。
当 externalsType
为 commonjs
时,此示例将转换为 require('./math').subtract;
而当 externalsType
为 window
时,此示例将转换为 window["./math"]["subtract"];
与 字符串语法 类似,您可以在数组的第一项中使用 ${externalsType} ${libraryName}
语法指定外部库类型,例如
module.exports = {
//...
externals: {
subtract: ['commonjs ./math', 'subtract'],
},
};
module.exports = {
//...
externals: {
react: 'react',
},
// or
externals: {
lodash: {
commonjs: 'lodash',
amd: 'lodash',
root: '_', // indicates global variable
},
},
// or
externals: {
subtract: {
root: ['math', 'subtract'],
},
},
};
此语法用于描述外部库可以提供的各种可能方式。这里的 lodash
在 AMD 和 CommonJS 模块系统中可用作 lodash
,但在全局变量形式中可用作 _
。这里的 subtract
可通过全局 math
对象下的 subtract
属性获得(例如 window['math']['subtract']
)。
function ({ context, request, contextInfo, getResolve }, callback)
function ({ context, request, contextInfo, getResolve }) => promise
5.15.0+定义你自己的函数来控制要从 webpack 外部化的行为可能很有用。例如,webpack-node-externals 排除了 node_modules
目录中的所有模块,并提供了允许列出包的选项。
以下是函数可以接收的参数
ctx
(object
):包含文件详细信息的对象。ctx.context
(string
):包含导入的文件的目录。ctx.request
(string
):正在请求的导入路径。ctx.contextInfo
(object
):包含有关发行者(例如层和编译器)的信息ctx.getResolve
5.15.0+:使用当前解析器选项获取解析函数。callback
(function (err, result, type)
):用于指示模块应如何外部化的回调函数。回调函数采用三个参数
err
(Error
):用于指示在外部化导入时是否发生错误。如果发生错误,这应该是使用的唯一参数。result
(string
[string]
object
):使用其他外部格式(string
、[string]
或 object
)描述外部模块type
(string
):指示模块 外部类型 的可选参数(如果尚未在 result
参数中指示)。例如,要将所有导入项外部化,其中导入路径与正则表达式匹配,可以执行以下操作
webpack.config.js
module.exports = {
//...
externals: [
function ({ context, request }, callback) {
if (/^yourregex$/.test(request)) {
// Externalize to a commonjs module using the request path
return callback(null, 'commonjs ' + request);
}
// Continue without externalizing the import
callback();
},
],
};
使用不同模块格式的其他示例
webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// The external is a `commonjs2` module located in `@scope/library`
callback(null, '@scope/library', 'commonjs2');
},
],
};
webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// The external is a global variable called `nameOfGlobal`.
callback(null, 'nameOfGlobal');
},
],
};
webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// The external is a named export in the `@scope/library` module.
callback(null, ['@scope/library', 'namedexport'], 'commonjs');
},
],
};
webpack.config.js
module.exports = {
externals: [
function (ctx, callback) {
// The external is a UMD module
callback(null, {
root: 'componentsGlobal',
commonjs: '@scope/components',
commonjs2: '@scope/components',
amd: 'components',
});
},
],
};
与给定正则表达式匹配的每个依赖项都将从输出包中排除。
webpack.config.js
module.exports = {
//...
externals: /^(jquery|\$)$/i,
};
在这种情况下,任何名为jQuery
的依赖项,无论大小写,或$
都将被外部化。
有时,您可能希望使用上述语法组合。这可以通过以下方式完成
webpack.config.js
module.exports = {
//...
externals: [
{
// String
react: 'react',
// Object
lodash: {
commonjs: 'lodash',
amd: 'lodash',
root: '_', // indicates global variable
},
// [string]
subtract: ['./math', 'subtract'],
},
// Function
function ({ context, request }, callback) {
if (/^yourregex$/.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
},
// Regex
/^(jquery|\$)$/i,
],
};
有关如何使用此配置的更多信息,请参阅有关如何编写库的文章。
function
object
按层指定外部项。
webpack.config.js
module.exports = {
externals: {
byLayer: {
layer: {
external1: 'var 43',
},
},
},
};
string = 'var'
指定外部项的默认类型。amd
、umd
、system
和jsonp
外部项取决于output.libraryTarget
被设置为相同的值,例如,您只能在amd
库中使用amd
外部项。
支持的类型
'amd'
'amd-require'
'assign'
- 与'var'
相同'commonjs'
'commonjs-module'
'global'
'import'
- 使用import()
加载本机 EcmaScript 模块(异步模块)'jsonp'
'module'
'node-commonjs'
'promise'
- 与'var'
相同,但等待结果(异步模块)'self'
'system'
'script'
'this'
'umd'
'umd2'
'var'
'window'
webpack.config.js
module.exports = {
//...
externalsType: 'promise',
};
将外部模块的默认类型指定为 'commonjs'
。Webpack 将为模块中使用的外部模块生成类似 const X = require('...')
的代码。
import fs from 'fs-extra';
webpack.config.js
module.exports = {
// ...
externalsType: 'commonjs',
externals: {
'fs-extra': 'fs-extra',
},
};
将生成类似以下内容
const fs = require('fs-extra');
请注意,输出包中将包含 require()
。
将外部模块的默认类型指定为 'global'
。Webpack 将在 globalObject
上将外部模块读取为全局变量。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'global',
externals: {
jquery: '$',
},
output: {
globalObject: 'global',
},
};
将生成类似以下内容
const jq = global['$'];
jq('.my-element').animate(/* ... */);
将外部模块的默认类型指定为 'module'
。Webpack 将为模块中使用的外部模块生成类似 import * as X from '...'
的代码。
请务必先启用 experiments.outputModule
,否则 webpack 将抛出错误。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
experiments: {
outputModule: true,
},
externalsType: 'module',
externals: {
jquery: 'jquery',
},
};
将生成类似以下内容
import * as __WEBPACK_EXTERNAL_MODULE_jquery__ from 'jquery';
const jq = __WEBPACK_EXTERNAL_MODULE_jquery__['default'];
jq('.my-element').animate(/* ... */);
请注意,输出包中将包含 import
语句。
将外部模块的默认类型指定为 'node-commonjs'
。Webpack 将从 'module'
导入 createRequire
以构造一个 require 函数,用于加载模块中使用的外部模块。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.export = {
experiments: {
outputModule: true,
},
externalsType: 'node-commonjs',
externals: {
jquery: 'jquery',
},
};
将生成类似以下内容
import { createRequire } from 'module';
const jq = createRequire(import.meta.url)('jquery');
jq('.my-element').animate(/* ... */);
请注意,输出包中将包含 import
语句。
将外部模块的默认类型指定为 'promise'
。Webpack 将将外部模块读取为全局变量(类似于 'var'
),并对其执行 await
。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'promise',
externals: {
jquery: '$',
},
};
将生成类似以下内容
const jq = await $;
jq('.my-element').animate(/* ... */);
将外部的默认类型指定为 'self'
。Webpack 会将外部作为 self
对象上的全局变量读取。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'self',
externals: {
jquery: '$',
},
};
将生成类似以下内容
const jq = self['$'];
jq('.my-element').animate(/* ... */);
将外部的默认类型指定为 'script'
。Webpack 会将外部加载为脚本,使用 HTML <script>
元素公开预定义的全局变量。加载脚本后,将移除 <script>
标记。
module.exports = {
externalsType: 'script',
externals: {
packageName: [
'http://example.com/script.js',
'global',
'property',
'property',
], // properties are optional
},
};
如果你不打算指定任何属性,还可以使用快捷语法
module.exports = {
externalsType: 'script',
externals: {
packageName: 'global@http://example.com/script.js', // no properties here
},
};
请注意,output.publicPath
不会添加到提供的 URL 中。
我们从 CDN 加载一个 lodash
webpack.config.js
module.exports = {
// ...
externalsType: 'script',
externals: {
lodash: ['https://cdn.jsdelivr.net.cn/npm/[email protected]/lodash.min.js', '_'],
},
};
然后在代码中使用它
import _ from 'lodash';
console.log(_.head([1, 2, 3]));
以下是如何为上述示例指定属性
module.exports = {
// ...
externalsType: 'script',
externals: {
lodash: [
'https://cdn.jsdelivr.net.cn/npm/[email protected]/lodash.min.js',
'_',
'head',
],
},
};
当你 import
lodash
时,本地变量 head
和全局变量 window._
都会公开
import head from 'lodash';
console.log(head([1, 2, 3])); // logs 1 here
console.log(window._.head(['a', 'b'])); // logs a here
将外部的默认类型指定为 'this'
。Webpack 会将外部作为 this
对象上的全局变量读取。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'this',
externals: {
jquery: '$',
},
};
将生成类似以下内容
const jq = this['$'];
jq('.my-element').animate(/* ... */);
将外部的默认类型指定为 'var'
。Webpack 会将外部作为全局变量读取。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'var',
externals: {
jquery: '$',
},
};
将生成类似以下内容
const jq = $;
jq('.my-element').animate(/* ... */);
将外部的默认类型指定为 'window'
。Webpack 会将外部作为 window
对象上的全局变量读取。
import jq from 'jquery';
jq('.my-element').animate(/* ... */);
webpack.config.js
module.exports = {
// ...
externalsType: 'window',
externals: {
jquery: '$',
},
};
将生成类似以下内容
const jq = window['$'];
jq('.my-element').animate(/* ... */);
对象
为特定目标启用外部预设。
选项 | 说明 | 输入类型 |
---|---|---|
electron | 将主上下文中和预加载上下文中常见的 electron 内置模块(如 electron 、ipc 或 shell )视为外部模块,并在使用时通过 require() 加载它们。 | 布尔值 |
electronMain | 将主上下文中 electron 内置模块(如 app 、ipc-main 或 shell )视为外部模块,并在使用时通过 require() 加载它们。 | 布尔值 |
electronPreload | 将预加载上下文中 electron 内置模块(如 web-frame 、ipc-renderer 或 shell )视为外部模块,并在使用时通过 require() 加载它们。 | 布尔值 |
electronRenderer | 将渲染器上下文中 electron 内置模块(如 web-frame 、ipc-renderer 或 shell )视为外部模块,并在使用时通过 require() 加载它们。 | 布尔值 |
节点 | 将 node.js 内置模块(如 fs 、path 或 vm )视为外部模块,并在使用时通过 require() 加载它们。 | 布尔值 |
nwjs | 将 NW.js 旧版 nw.gui 模块视为外部模块,并在使用时通过 require() 加载它。 | 布尔值 |
web | 将对 http(s)://... 和 std:... 的引用视为外部模块,并在使用时通过 import 加载它们。(请注意,这会更改执行顺序,因为外部模块会在块中的任何其他代码之前执行)。 | 布尔值 |
webAsync | 将对 http(s)://... 和 std:... 的引用视为外部模块,并在使用时通过 async import() 加载它们。(请注意,此外部类型是一个 async 模块,它对执行有各种影响)。 | 布尔值 |
请注意,如果你打算使用这些与 node.js 相关的预设输出 ES 模块,webpack 会将默认 externalsType
设置为 node-commonjs
,它会使用 createRequire
来构造一个 require 函数,而不是使用 require()
。
示例
使用 node
预设不会捆绑内置模块,而是将它们视为外部模块,并在使用时通过 require()
加载它们。
webpack.config.js
module.exports = {
// ...
externalsPresets: {
node: true,
},
};