Movatterモバイル変換


[0]ホーム

URL:


webpack logo
ag grid
ag charts

Externals

Theexternals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's (any end-user application) environment. This feature is typically most useful tolibrary developers, however there are a variety of applications for it.

externals

stringobjectfunctionRegExp[string, object, function, RegExp]

Prevent bundling of certainimported packages and instead retrieve theseexternal dependencies at runtime.

For example, to includejQuery from a CDN instead of bundling it:

index.html

<scriptsrc="https://code.jquery.com/jquery-3.1.0.js"integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="crossorigin="anonymous"></script>

webpack.config.js

module.exports={// ...  externals:{    jquery:"jQuery",},};

This leaves any dependent modules unchanged, i.e. the code shown below will still work:

import $from"jquery";$(".my-element").animate(/* ... */);

The property namejquery specified underexternals in the abovewebpack.config.js indicates that the modulejquery inimport $ from 'jquery' should be excluded from bundling. In order to replace this module, the valuejQuery will be used to retrieve a globaljQuery variable, as the default external library type isvar, seeexternalsType.

While we showed an example consuming external global variable above, the external can actually be available in any of these forms: global variable, CommonJS, AMD, ES2015 Module, see more inexternalsType.

string

Depending on theexternalsType, this could be the name of the global variable (see'global','this','var','window') or the name of the module (seeamd,commonjs,module,umd).

You can also use the shortcut syntax if you're defining only 1 external:

module.exports={// ...  externals:"jquery",};

equals to

module.exports={// ...  externals:{    jquery:"jquery",},};

You can specify theexternal library type to the external with the${externalsType} ${libraryName} syntax. It will override the default external library type specified in theexternalsType option.

For example, if the external library is aCommonJS module, you can specify

module.exports={// ...  externals:{    jquery:"commonjs jquery",},};

[string]

module.exports={// ...  externals:{    subtract:["./math","subtract"],},};

subtract: ['./math', 'subtract'] allows you select part of a module, where./math is the module and your bundle only requires the subset under thesubtract variable.

When theexternalsType iscommonjs, this example would translate torequire('./math').subtract; while when theexternalsType iswindow, this example would translate towindow["./math"]["subtract"];

Similar to thestring syntax, you can specify the external library type with the${externalsType} ${libraryName} syntax, in the first item of the array, for example:

module.exports={// ...  externals:{    subtract:["commonjs ./math","subtract"],},};

object

warning

An object with{ root, amd, commonjs, ... } is only allowed forlibraryTarget: 'umd' andexternalsType: 'umd'. It's not allowed for other library targets.

module.exports={// ...// or  externals:{    react:"react",},};
module.exports={// ...// or  externals:{    lodash:{      commonjs:"lodash",      amd:"lodash",      root:"_",// indicates global variable},},};
module.exports={// ...// or  externals:{    subtract:{      root:["math","subtract"],},},};

This syntax is used to describe all the possible ways that an external library can be made available.lodash here is available aslodash under AMD and CommonJS module systems but available as_ in a global variable form.subtract here is available via the propertysubtract under the globalmath object (e.g.window['math']['subtract']).

function

  • function ({ context, request, contextInfo, getResolve }, callback)
  • function ({ context, request, contextInfo, getResolve }) => promise5.15.0+

It might be useful to define your own function to control the behavior of what you want to externalize from webpack.webpack-node-externals, for example, excludes all modules from thenode_modules directory and provides options to allowlist packages.

Here're arguments the function can receive:

  • ctx (object): Object containing details of the file.
    • ctx.context (string): The directory of the file which contains the import.
    • ctx.request (string): The import path being requested.
    • ctx.contextInfo (object): Contains information about the issuer (e.g. the layer and compiler)
    • ctx.getResolve5.15.0+: Get a resolve function with the current resolver options.
  • callback (function (err, result, type)): Callback function used to indicate how the module should be externalized.

The callback function takes three arguments:

  • err (Error): Used to indicate if there has been an error while externalizing the import. If there is an error, this should be the only parameter used.
  • result (string[string]object): Describes the external module with the other external formats (string,[string], orobject)
  • type (string): Optional parameter that indicates the moduleexternal type (if it has not already been indicated in theresult parameter).

As an example, to externalize all imports where the import path matches a regular expression you could do the following:

webpack.config.js

module.exports={// ...  externals:[function({ context, request}, callback){if(/^yourregex$/.test(request)){// Externalize to a commonjs module using the request pathreturncallback(null,`commonjs${request}`);}// Continue without externalizing the importcallback();},],};

Other examples using different module formats:

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 modulecallback(null,{        root:"componentsGlobal",        commonjs:"@scope/components",        commonjs2:"@scope/components",        amd:"components",});},],};

RegExp

Every dependency that matches the given regular expression will be excluded from the output bundles.

webpack.config.js

module.exports={// ...  externals:/^(jquery|\$)$/i,};

In this case, any dependency namedjQuery, capitalized or not, or$ would be externalized.

Combining syntaxes

Sometimes you may want to use a combination of the above syntaxes. This can be done in the following manner:

webpack.config.js

module.exports={// ...  externals:[{// String      react:"react",// Object      lodash:{        commonjs:"lodash",        amd:"lodash",        root:"_",// indicates global variable},// [string]      subtract:["./math","subtract"],},// Functionfunction({ context, request}, callback){if(/^yourregex$/.test(request)){returncallback(null,`commonjs${request}`);}callback();},// Regex/^(jquery|\$)$/i,],};
warning

Default type will be used if you specifyexternals without a type e.g.externals: { react: 'react' } instead ofexternals: { react: 'commonjs-module react' }.

For more information on how to use this configuration, please refer to the article onhow to author a library.

byLayer

functionobject

Specify externals by layer.

webpack.config.js

module.exports={  externals:{    byLayer:{      layer:{        external1:"var 43",},},},};

externalsType

string = 'var'

Specify the default type of externals.amd,umd,system andjsonp externalsdepend on theoutput.libraryTarget being set to the same value e.g. you can only consumeamd externals within anamd library.

Supported types:

webpack.config.js

module.exports={// ...  externalsType:"promise",};

externalsType.commonjs

Specify the default type of externals as'commonjs'. Webpack will generate code likeconst X = require('...') for externals used in a module.

Example

import fsfrom"fs-extra";

webpack.config.js

module.exports={// ...  externalsType:"commonjs",  externals:{"fs-extra":"fs-extra",},};

Will generate into something like:

const fs=require("fs-extra");

Note that there will be arequire() in the output bundle.

externalsType.global

Specify the default type of externals as'global'. Webpack will read the external as a global variable on theglobalObject.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"global",  externals:{    jquery:"$",},  output:{    globalObject:"global",},};

Will generate into something like

const jq= globalThis.$;jq(".my-element").animate(/* ... */);

externalsType.module

Specify the default type of externals as'module'. Webpack will generate code likeimport * as X from '...' for externals used in a module.

Make sure to enableexperiments.outputModule first, otherwise webpack will throw errors.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={  experiments:{    outputModule:true,},  externalsType:"module",  externals:{    jquery:"jquery",},};

Will generate into something like

import*as __WEBPACK_EXTERNAL_MODULE_jquery__from"jquery";const jq= __WEBPACK_EXTERNAL_MODULE_jquery__.default;jq(".my-element").animate(/* ... */);

Note that there will be animport statement in the output bundle.

externalsType.import

5.94.0+

Specify the default type of externals as'import'. Webpack will generate code likeimport('...') for externals used in a module.

Example

asyncfunctionfoo(){const jq=awaitimport("jQuery");jq(".my-element").animate(/* ... */);}

webpack.config.js

module.exports={  externalsType:"import",  externals:{    jquery:"jquery",},};

Will generate something like below:

const __webpack_modules__={jQuery:(module)=>{    module.exports=import("jQuery");},};// webpack runtime...asyncfunctionfoo(){const jq=await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__,"jQuery"),);jq(".my-element").animate(/* ... */);}

Note that the output bundle will have animport() statement.

externalsType.module-import

5.94.0+

Specify the default type of externals as'module-import'. This combines'module' and'import'. Webpack will automatically detect the type of import syntax, setting it to'module' for static imports and'import' for dynamic imports.

Ensure to enableexperiments.outputModule first if static imports exist, otherwise, webpack will throw errors.

Example

import{ attempt}from"lodash";asyncfunctionfoo(){const jq=awaitimport("jQuery");attempt(()=>jq(".my-element").animate(/* ... */));}

webpack.config.js

module.exports={  externalsType:"module-import",  externals:{    jquery:"jquery",    lodash:"lodash",},};

Will generate something like below:

import*as __WEBPACK_EXTERNAL_MODULE_lodash__from"lodash";const lodash= __WEBPACK_EXTERNAL_MODULE_jquery__;const __webpack_modules__={jQuery:(module)=>{    module.exports=import("jQuery");},};// webpack runtime...asyncfunctionfoo(){const jq=await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__,"jQuery"),);(0, lodash.attempt)(()=>jq(".my-element").animate(/* ... */));}

Note that the output bundle will have animport orimport() statement.

When a module is not imported viaimport orimport(), webpack will use the"module" externals type as a fallback. If you want to use a different kind of externals as a fallback, you can specify it with a function in theexternals option. For example:

module.exports={  externalsType:"module-import",  externals:[function({ request, dependencyType}, callback){if(dependencyType==="commonjs"){returncallback(null,`node-commonjs${request}`);}callback();},],};

externalsType.node-commonjs

Specify the default type of externals as'node-commonjs'. Webpack will importcreateRequire from'module' to construct a require function for loading externals used in a module.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.export={  experiments:{    outputModule:true,},  externalsType:"node-commonjs",  externals:{    jquery:"jquery",},};

Will generate into something like

import{ createRequire}from"node:module";const jq=createRequire(import.meta.url)("jquery");jq(".my-element").animate(/* ... */);

Note that there will be animport statement in the output bundle.

This is useful when dependencies rely on Node.js built-in modules or require a CommonJS-stylerequire function to preserve prototypes, which is necessary for functions likeutil.inherits. Refer tothis issue for more details.

For code that relies on prototype structures, like:

functionChunkStream(){Stream.call(this);}util.inherits(ChunkStream, Stream);

You can usenode-commonjs to ensure that the prototype chain is preserved:

const{ builtinModules}=require("node:module");module.exports={  experiments:{ outputModule:true},  externalsType:"node-commonjs",externals:({ request}, callback)=>{if(request.startsWith("node:")|| builtinModules.includes(request)){returncallback(null,`node-commonjs${request}`);}callback();},};

This produces something like:

import{ createRequireas __WEBPACK_EXTERNAL_createRequire}from"node:module";const __webpack_modules__={// .../***/2613:/***/(module)=>{    module.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream",);/***/},// ...};

This setup keeps the prototype structure intact, resolving issues with Node.js built-ins.

externalsType.promise

Specify the default type of externals as'promise'. Webpack will read the external as a global variable (similar to'var') andawait for it.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"promise",  externals:{    jquery:"$",},};

Will generate into something like

const jq=await $;jq(".my-element").animate(/* ... */);

externalsType.self

Specify the default type of externals as'self'. Webpack will read the external as a global variable on theself object.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"self",  externals:{    jquery:"$",},};

Will generate into something like

const jq= globalThis.$;jq(".my-element").animate(/* ... */);

externalsType.script

Specify the default type of externals as'script'. Webpack will load the external as a script exposing predefined global variables with HTML<script> element. The<script> tag would be removed after the script has been loaded.

Syntax

module.exports={  externalsType:"script",  externals:{    packageName:["http://example.com/script.js","global","property","property",],// properties are optional},};

You can also use the shortcut syntax if you're not going to specify any properties:

module.exports={  externalsType:"script",  externals:{    packageName:"global@http://example.com/script.js",// no properties here},};

Note thatoutput.publicPath won't be added to the provided URL.

Example

Let's load alodash from CDN:

webpack.config.js

module.exports={// ...  externalsType:"script",  externals:{    lodash:["https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js","_"],},};

Then use it in code:

import _from"lodash";console.log(_.head([1,2,3]));

Here's how we specify properties for the above example:

module.exports={// ...  externalsType:"script",  externals:{    lodash:["https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js","_","head",],},};

Both local variablehead and globalwindow._ will be exposed when youimportlodash:

import headfrom"lodash";console.log(head([1,2,3]));// logs 1 hereconsole.log(globalThis._.head(["a","b"]));// logs a here
tip

When loading code with HTML<script> tags, the webpack runtime will try to find an existing<script> tag that matches thesrc attribute or has a specificdata-webpack attribute. For chunk loadingdata-webpack attribute would have value of'[output.uniqueName]:chunk-[chunkId]' while external script has value of'[output.uniqueName]:[global]'.

tip

Options likeoutput.chunkLoadTimeout,output.crossOriginLoading andoutput.scriptType will also have effect on the external scripts loaded this way.

externalsType.this

Specify the default type of externals as'this'. Webpack will read the external as a global variable on thethis object.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"this",  externals:{    jquery:"$",},};

Will generate into something like

const jq=this.$;jq(".my-element").animate(/* ... */);

externalsType.var

Specify the default type of externals as'var'. Webpack will read the external as a global variable.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"var",  externals:{    jquery:"$",},};

Will generate into something like

const jq= $;jq(".my-element").animate(/* ... */);

externalsType.window

Specify the default type of externals as'window'. Webpack will read the external as a global variable on thewindow object.

Example

import jqfrom"jquery";jq(".my-element").animate(/* ... */);

webpack.config.js

module.exports={// ...  externalsType:"window",  externals:{    jquery:"$",},};

Will generate into something like

const jq= globalThis.$;jq(".my-element").animate(/* ... */);

externalsPresets

object

Enable presets of externals for specific targets.

OptionDescriptionInput Type
electronTreat common electron built-in modules in main and preload context likeelectron,ipc orshell as external and load them viarequire() when used.boolean
electronMainTreat electron built-in modules in the main context likeapp,ipc-main orshell as external and load them viarequire() when used.boolean
electronPreloadTreat electron built-in modules in the preload context likeweb-frame,ipc-renderer orshell as external and load them via require() when used.boolean
electronRendererTreat electron built-in modules in the renderer context likeweb-frame,ipc-renderer orshell as external and load them viarequire() when used.boolean
nodeTreat node.js built-in modules likefs,path orvm as external and load them viarequire() when used.boolean
nwjsTreatNW.js legacynw.gui module as external and load it viarequire() when used.boolean
webTreat references tohttp(s)://... andstd:... as external and load them viaimport when used.(Note that this changes execution order as externals are executed before any other code in the chunk).boolean
webAsyncTreat references tohttp(s)://... andstd:... as external and load them viaasync import() when used(Note that this external type is anasync module, which has various effects on the execution).boolean

Note that if you're going to output ES Modules with those node.js-related presets, webpack will set the defaultexternalsType tonode-commonjs which would usecreateRequire to construct a require function instead of usingrequire().

Example

Usingnode preset will not bundle built-in modules and treats them as external and loads them viarequire() when used.

webpack.config.js

module.exports={// ...  externalsPresets:{    node:true,},};

18 Contributors

sokraskipjackpksjcefadysamirsadekbyzykzefmanMistyyyyjamesgeorge007tanhauhausnitin315beejunkEugeneHlushkochenxsanpranshuchittorakinetifexanshumanvSaulSilverfi3ework

[8]ページ先頭

©2009-2026 Movatter.jp