This section covers all methods available in code compiled with webpack. When using webpack to bundle your application, you can pick from a variety of module syntax styles includingES6,CommonJS, andAMD.
While webpack supports multiple module syntaxes, we recommend following a single syntax for consistency and to avoid odd behaviors/bugs. Actually webpack would enforce the recommendation for.mjs files,.cjs files or.js files when their nearest parentpackage.json file contains a"type" field with a value of either"module" or"commonjs". Please pay attention to these enforcements before you read on:
.mjs or.js with"type": "module" inpackage.jsonrequire,module.exports orexportsimport './src/App.mjs' instead ofimport './src/App' (you can disable this enforcement withRule.resolve.fullySpecified).cjs or.js with"type": "commonjs" inpackage.jsonimport norexport is available.wasm with"type": "module" inpackage.jsonVersion 2 of webpack supports ES6 module syntax natively, meaning you can useimport andexport without a tool like babel to handle this for you. Keep in mind that you will still probably need babel for other ES6+ features. The following methods are supported by webpack:
Staticallyimport theexports of another module.
import MyModulefrom'./my-module.js';import{ NamedExport}from'./other-module.js';The keyword here isstatically. A normalimport statement cannot be used dynamically within other logic or contain variables. See thespec for more information andimport() below for dynamic usage.
You can alsoimport Data URI:
import'data:text/javascript;charset=utf-8;base64,Y29uc29sZS5sb2coJ2lubGluZSAxJyk7';import{ number, fn,}from'data:text/javascript;charset=utf-8;base64,ZXhwb3J0IGNvbnN0IG51bWJlciA9IDQyOwpleHBvcnQgY29uc3QgZm4gPSAoKSA9PiAiSGVsbG8gd29ybGQiOw==';Export anything as adefault or named export.
// Named exportsexportvar Count=5;exportfunctionMultiply(a, b){return a* b;}// Default exportexportdefault{// Some data...};function(string path):Promise
Dynamically load modules. Calls toimport() are treated as split points, meaning the requested module and its children are split out into a separate chunk.
TheES2015 Loader spec definesimport() as method to load ES2015 modules dynamically on runtime.
if(module.hot){import('lodash').then((_)=>{// Do something with lodash (a.k.a '_')...});}This feature relies onPromise internally. If you useimport() with older browsers, remember to shimPromise using a polyfill such ases6-promise orpromise-polyfill.
It is not possible to use a fully dynamic import statement, such asimport(foo). Becausefoo could potentially be any path to any file in your system or project.
Theimport() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on animport() call is included.For example,import(`./locale/${language}.json`) will only bundle all.json files in the./locale directory and subdirectories into the new chunk and exclude files with other file extensions. At run time, when the variablelanguage has been computed, any file likeenglish.json orgerman.json will be available for consumption.
// imagine we had a method to get language from cookies or other storageconst language=detectVisitorLanguage();import(`./locale/${language}.json`).then((module)=>{// do something with the translations});Using thewebpackInclude andwebpackExclude options allows you to add regex patterns that reduce the number of files that webpack will bundle for this import.
By adding comments to the import, we can do things such as name our chunk or select different modes. For a full list of these magic comments see the code below followed by an explanation of what these comments do.
// Single targetimport(/* webpackChunkName: "my-chunk-name" *//* webpackMode: "lazy" *//* webpackExports: ["default", "named"] *//* webpackFetchPriority: "high" */'module');// Multiple possible targetsimport(/* webpackInclude: /\.json$/ *//* webpackExclude: /\.noimport\.json$/ *//* webpackChunkName: "my-chunk-name" *//* webpackMode: "lazy" *//* webpackPrefetch: true *//* webpackPreload: true */`./locale/${language}`);import(/* webpackIgnore: true */'ignored-module.js');Single line comments (//) are also supported. JSDoc comments (/** */) are not.
JavaScript Usage
Disables dynamic import parsing when set totrue.
When usingimport.meta.url, it does not remain as-is; instead, it gets replaced based on thebaseURI. For modules, it is replaced withnew URL("./", import.meta.url), and for other cases, it defaults todocument.baseURI. This ensures that relative URLs work correctly, aligning with the base URL context.
import(/* webpackIgnore: true */'ignored-module.js');newURL(/* webpackIgnore: true */'file1.css',import.meta.url);Note that settingwebpackIgnore totrue opts out of code splitting.
CSS Usage
ThewebpackIgnore comment can control whether webpack processes a specific import or URL reference.It works in certain cases out of the box butdoesn’t support all cases by default due to performance reasons.
We supportwebpackIgnore in the following cases:
@import/* webpackIgnore: false */url(./basic.css);.class{color: red;background:/* webpackIgnore: true */url('./url/img.png');}.class{background-image:image-set(/*webpackIgnore: true*/url(./url/img1x.png) 1x,url(./url/img2x.png) 2x,url(./url/img3x.png) 3x);}For other CSS scenarios,css-loader fully supportswebpackIgnore, allowing more flexibility if needed.
A name for the new chunk. Since webpack 2.6.0, the placeholders[index] and[request] are supported within the given string to an incremented number or the actual resolved filename respectively. Adding this comment will cause our separate chunk to be named [my-chunk-name].js instead of [id].js.
SetfetchPriority for specific dynamic imports. It's also possible to set a global default value for all dynamic imports by using themodule.parser.javascript.dynamicImportFetchPriority option.
import(/* webpackFetchPriority: "high" */'path/to/module');Since webpack 2.6.0, different modes for resolving dynamic imports can be specified. The following options are supported:
'lazy' (default): Generates a lazy-loadable chunk for eachimport()ed module.'lazy-once': Generates a single lazy-loadable chunk that can satisfy all calls toimport(). The chunk will be fetched on the first call toimport(), and subsequent calls toimport() will use the same network response. Note that this only makes sense in the case of a partially dynamic statement, e.g.import(`./locales/${language}.json`), where multiple module paths that can potentially be requested.'eager': Generates no extra chunk. All modules are included in the current chunk and no additional network requests are made. APromise is still returned but is already resolved. In contrast to a static import, the module isn't executed until the call toimport() is made.'weak': Tries to load the module if the module function has already been loaded in some other way (e.g. another chunk imported it or a script containing the module was loaded). APromise is still returned, but only successfully resolves if the chunks are already on the client. If the module is not available, thePromise is rejected. A network request will never be performed. This is useful for universal rendering when required chunks are always manually served in initial requests (embedded within the page), but not in cases where app navigation will trigger an import not initially served.Tells the browser that the resource is probably needed for some navigation in the future. Check out the guide for more information onhow webpackPrefetch works.
Tells the browser that the resource might be needed during the current navigation. Check out the guide for more information onhow webpackPreload works.
Note that all options can be combined like so/* webpackMode: "lazy-once", webpackChunkName: "all-i18n-data" */. This is wrapped in a JavaScript object and executed usingnode VM. You do not need to add curly brackets.
A regular expression that will be matched against during import resolution. Only modules that matchwill be bundled.
A regular expression that will be matched against during import resolution. Any module that matcheswill not be bundled.
Note thatwebpackInclude andwebpackExclude options do not interfere with the prefix. eg:./locale.
Tells webpack to only bundle the specified exports of a dynamicallyimport()ed module. It can decrease the output size of a chunk. Available sincewebpack 5.0.0-beta.18.
webpackExports cannot be used with destructuring assignments.
The goal of CommonJS is to specify an ecosystem for JavaScript outside the browser. The following CommonJS methods are supported by webpack:
require(dependency: String);Synchronously retrieve the exports from another module. The compiler will ensure that the dependency is available in the output bundle.
var $=require('jquery');var myModule=require('my-module');It's possible to enable magic comments forrequire as well, seemodule.parser.javascript.commonjsMagicComments for more.
Using it asynchronously may not have the expected effect.
require.resolve(dependency: String);Synchronously retrieve a module's ID. The compiler will ensure that the dependency is available in the output bundle. It is recommended to treat it as an opaque value which can only be used withrequire.cache[id] or__webpack_require__(id) (best to avoid such usage).
Module ID's type can be anumber or astring depending on theoptimization.moduleIds configuration.
Seemodule.id for more information.
Multiple requires of the same module result in only one module execution and only one export. Therefore a cache in the runtime exists. Removing values from this cache causes new module execution and a new export.
This is only needed in rare cases for compatibility!
var d1=require('dependency');require('dependency')=== d1;delete require.cache[require.resolve('dependency')];require('dependency')!== d1;// in file.jsrequire.cache[module.id]=== module;require('./file.js')=== module.exports;delete require.cache[module.id];require.cache[module.id]===undefined;require('./file.js')!== module.exports;// in theory; in praxis this causes a stack overflowrequire.cache[module.id]!== module;require.ensure() is specific to webpack and superseded byimport().
require.ensure( dependencies: String[],callback:function(require),errorCallback:function(error), chunkName: String)Split out the givendependencies to a separate bundle that will be loaded asynchronously. When using CommonJS module syntax, this is the only way to dynamically load dependencies. Meaning, this code can be run within execution, only loading thedependencies if certain conditions are met.
This feature relies onPromise internally. If you userequire.ensure with older browsers, remember to shimPromise using a polyfill such ases6-promise orpromise-polyfill.
var a=require('normal-dep');if(module.hot){ require.ensure(['b'],function(require){var c=require('c');// Do something special...});}The following parameters are supported in the order specified above:
dependencies: An array of strings declaring all modules required for the code in thecallback to execute.callback: A function that webpack will execute once the dependencies are loaded. An implementation of therequire function is sent as a parameter to this function. The function body can use this to furtherrequire() modules it needs for execution.errorCallback: A function that is executed when webpack fails to load the dependencies.chunkName: A name given to the chunk created by this particularrequire.ensure(). By passing the samechunkName to variousrequire.ensure() calls, we can combine their code into a single chunk, resulting in only one bundle that the browser must load.Although the implementation ofrequire is passed as an argument to thecallback function, using an arbitrary name e.g.require.ensure([], function(request) { request('someModule'); }) isn't handled by webpack's static parser. Userequire instead, e.g.require.ensure([], function(require) { require('someModule'); }).
Asynchronous Module Definition (AMD) is a JavaScript specification that defines an interface for writing and loading modules. The following AMD methods are supported by webpack:
define([name: String],[dependencies: String[]],factoryMethod:function(...))Ifdependencies are provided,factoryMethod will be called with the exports of each dependency (in the same order). Ifdependencies are not provided,factoryMethod is called withrequire,exports andmodule (for compatibility!). If this function returns a value, this value is exported by the module. The compiler ensures that each dependency is available.
Note that webpack ignores thename argument.
define(['jquery','my-module'],function($, myModule){// Do something with $ and myModule...// Export a functionreturnfunctiondoSomething(){// ...};});This CANNOT be used in an asynchronous function.
define(value:!Function)This will export the providedvalue. Thevalue here can be anything except a function.
define({ answer:42,});This CANNOT be used in an async function.
require(dependencies: String[],[callback:function(...)])Similar torequire.ensure, this will split the givendependencies into a separate bundle that will be loaded asynchronously. Thecallback will be called with the exports of each dependency in thedependencies array.
This feature relies onPromise internally. If you use AMD with older browsers (e.g. Internet Explorer 11), remember to shimPromise using a polyfill such ases6-promise orpromise-polyfill.
require(['b'],function(b){var c=require('c');});There is no option to provide a chunk name.
The internalLabeledModulesPlugin enables you to use the following methods for exporting and requiring within your modules:
Export the givenvalue. The label can occur before a function declaration or a variable declaration. The function name or variable name is the identifier under which the value is exported.
export:var answer=42;export:functionmethod(value){// Do something...};Using it in an async function may not have the expected effect.
Make all exports from the dependency available in the current scope. Therequire label can occur before a string. The dependency must export values with theexport label. CommonJS or AMD modules cannot be consumed.
some-dependency.js
export:var answer=42;export:functionmethod(value){// Do something...};require:'some-dependency';console.log(answer);method(...);Aside from the module syntaxes described above, webpack also allows a few custom, webpack-specific methods:
require.context((directory: String),(includeSubdirs: Boolean)/* optional, default true */,(filter: RegExp)/* optional, default /^\.\/.*$/, any file */,(mode: String)/* optional, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once', default 'sync' */);Specify a whole group of dependencies using a path to thedirectory, an option toincludeSubdirs, afilter for more fine grained control of the modules included, and amode to define the way how loading will work. Underlying modules can then be resolved later on:
var context= require.context('components',true,/\.html$/);var componentA= context.resolve('componentA');Ifmode is set to'lazy', the underlying modules will be loaded asynchronously:
var context= require.context('locales',true,/\.json$/,'lazy');context('localeA').then((locale)=>{// do something with locale});The full list of available modes and their behavior is described inimport() documentation.
require.include((dependency: String));Include adependency without executing it. This can be used for optimizing the position of a module in the output chunks.
require.include('a');require.ensure(['a','b'],function(require){/* ... */});require.ensure(['a','c'],function(require){/* ... */});This will result in the following output:
file.js andabcWithoutrequire.include('a') it would be duplicated in both anonymous chunks.
Similar torequire.resolve, but this won't pull themodule into the bundle. It's what is considered a "weak" dependency.
if(__webpack_modules__[require.resolveWeak('module')]){// Do something when module is available...}if(require.cache[require.resolveWeak('module')]){// Do something when module was loaded before...}// You can perform dynamic resolves ("context")// similarly to other require/import methods.const page='Foo';__webpack_modules__[require.resolveWeak(`./page/${page}`)];require.resolveWeak is the foundation ofuniversal rendering (SSR + Code Splitting), as used in packages such asreact-universal-component. It allows code to render synchronously on both the server and initial page-loads on the client. It requires that chunks are manually served or somehow available. It's able to require modules without indicating they should be bundled into a chunk. It's used in conjunction withimport() which takes over when user navigation triggers additional imports.
If the module source contains a require that cannot be statically analyzed, critical dependencies warning is emitted.
Example code:
someFn(require);require.bind(null);require(variable);