These options determine how the different types of modules within a project will be treated.
module.generator
It's possible to configure all generators' options in one place with a module.generator
.
webpack.config.js
module.exports = {
module: {
generator: {
'asset': {
// Generator options for asset modules
},
'asset/inline': {
// Generator options for asset/inline modules
},
'asset/resource': {
// Generator options for asset/resource modules
},
'javascript': {
// No generator options are supported for this module type yet
},
'javascript/auto': {
// ditto
},
'javascript/dynamic': {
// ditto
},
'javascript/esm': {
// ditto
},
// othersβ¦
}
}
};
Similar to the module.generator
, you can configure all parsers' options in one place with a module.parser
.
webpack.config.js
module.exports = {
module: {
parser: {
'asset': {
// Parser options for asset modules
},
'asset/inline': {
// No parser options are supported for this module type yet
},
'asset/resource': {
// ditto
},
'asset/source': {
// ditto
},
'javascript': {
// Parser options for javascript modules
// e.g, enable parsing of require.ensure syntax
requireEnsure: true
},
'javascript/auto': {
// ditto
},
'javascript/dynamic': {
// ditto
},
'javascript/esm': {
// ditto
},
// othersβ¦
}
}
};
Configure options for JavaScript parser.
module.exports = {
module: {
parser: {
javascript: {
// ...
commonjsMagicComments: true,
},
},
},
};
It's allowed to configure those options in Rule.parser
as well to target specific modules.
Enable magic comments support for CommonJS.
boolean
module.exports = {
module: {
parser: {
javascript: {
commonjsMagicComments: true,
},
}
},
};
Note that only webpackIgnore
comment is supported at the moment:
const x = require(/* webpackIgnore: true */ 'x');
module.noParse
RegExp
[RegExp]
function(resource)
string
[string]
Prevent webpack from parsing any files matching the given regular expression(s). Ignored files should not have calls to import
, require
, define
or any other importing mechanism. This can boost build performance when ignoring large libraries.
webpack.config.js
module.exports = {
//...
module: {
noParse: /jquery|lodash/,
}
};
module.exports = {
//...
module: {
noParse: (content) => /jquery|lodash/.test(content)
}
};
module.unsafeCache
boolean
function (module)
Cache the resolution of module requests. There are a couple of defaults for module.unsafeCache
:
false
if cache
is disabled.true
if cache
is enabled and the module appears to come from node modules, false
otherwise.webpack.config.js
module.exports = {
//...
module: {
unsafeCache: false,
}
};
module.rules
[Rule]
An array of Rules which are matched to requests when modules are created. These rules can modify how the module is created. They can apply loaders to the module, or modify the parser.
object
A Rule can be separated into three parts β Conditions, Results and nested Rules.
There are two input values for the conditions:
The resource: An absolute path to the file requested. It's already resolved according to the resolve
rules.
The issuer: An absolute path to the file of the module which requested the resource. It's the location of the import.
Example: When we import './style.css'
within app.js
, the resource is /path/to/style.css
and the issuer is /path/to/app.js
.
In a Rule the properties test
, include
, exclude
and resource
are matched with the resource and the property issuer
is matched with the issuer.
When using multiple conditions, all conditions must match.
Rule results are used only when the Rule condition matches.
There are two output values of a Rule:
These properties affect the loaders: loader
, options
, use
.
For compatibility also these properties: query
, loaders
.
The enforce
property affects the loader category. Whether it's a normal, pre- or post- loader.
The parser
property affects the parser options.
Nested rules can be specified under the properties rules
and oneOf
.
These rules are evaluated only when the parent Rule condition matches. Each nested rule can contain its own conditions.
The order of evaluation is as follows:
Rule.enforce
string
Possible values: 'pre' | 'post'
Specifies the category of the loader. No value means normal loader.
There is also an additional category "inlined loader" which are loaders applied inline of the import/require.
There are two phases that all loaders enter one after the other:
post, inline, normal, pre
. See Pitching Loader for details.pre, normal, inline, post
. Transformation on the source code of a module happens in this phase.All normal loaders can be omitted (overridden) by prefixing !
in the request.
All normal and pre loaders can be omitted (overridden) by prefixing -!
in the request.
All normal, post and pre loaders can be omitted (overridden) by prefixing !!
in the request.
// Disable normal loaders
import { a } from '!./file1.js';
// Disable preloaders and normal loaders
import { b } from '-!./file2.js';
// Disable all loaders
import { c } from '!!./file3.js';
Inline loaders and !
prefixes should not be used as they are non-standard. They may be used by loader generated code.
Rule.exclude
Exclude all modules matching any of these conditions. If you supply a Rule.exclude
option, you cannot also supply a Rule.resource
. See Rule.resource
and Condition.exclude
for details.
Rule.include
Include all modules matching any of these conditions. If you supply a Rule.include
option, you cannot also supply a Rule.resource
. See Rule.resource
and Condition.include
for details.
Rule.issuer
A Condition
to match against the module that issued the request. In the following example, the issuer
for the a.js
request would be the path to the index.js
file.
index.js
import A from './a.js';
This option can be used to apply loaders to the dependencies of a specific module or set of modules.
Rule.issuerLayer
Allows to filter/match by layer of the issuer.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
issuerLayer: 'other-layer',
}
]
}
};
Rule.layer
string
Specify the layer in which the module should be placed in.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /module-layer-change/,
layer: 'layer',
}
]
}
};
Rule.loader
Rule.loader
is a shortcut to Rule.use: [ { loader } ]
. See Rule.use
and UseEntry.loader
for details.
Rule.loaders
Rule.loaders
is an alias to Rule.use
. See Rule.use
for details.
Rule.mimetype
You can match config rules to data uri with mimetype
.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
mimetype: 'application/json',
type: 'json',
}
]
}
};
application/json
, text/javascript
, application/javascript
, application/node
and application/wasm
are already included by default as mimetype.
Rule.oneOf
An array of Rules
from which only the first matching Rule is used when the Rule matches.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
test: /\\.css$/,
oneOf: [
{
resourceQuery: /inline/, // foo.css?inline
use: 'url-loader'
},
{
resourceQuery: /external/, // foo.css?external
use: 'file-loader'
}
]
}
]
}
};
Rule.options
/ Rule.query
Rule.options
and Rule.query
are shortcuts to Rule.use: [ { options } ]
. See Rule.use
and UseEntry.options
for details.
Rule.parser
An object with parser options. All applied parser options are merged.
Parsers may inspect these options and disable or reconfigure themselves accordingly. Most of the default plugins interpret the values as follows:
false
disables the parser.true
or leaving it undefined
enables the parser.However, parser plugins may accept more than just a boolean. For example, the internal NodeStuffPlugin
can accept an object instead of true
to add additional options for a particular Rule.
Examples (parser options by the default plugins):
module.exports = {
//...
module: {
rules: [
{
//...
parser: {
amd: false, // disable AMD
commonjs: false, // disable CommonJS
system: false, // disable SystemJS
harmony: false, // disable ES2015 Harmony import/export
requireInclude: false, // disable require.include
requireEnsure: false, // disable require.ensure
requireContext: false, // disable require.context
browserify: false, // disable special handling of Browserify bundles
requireJs: false, // disable requirejs.*
node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc.
commonjsMagicComments: false, // disable magic comments support for CommonJS
node: {...}, // reconfigure [node](/configuration/node) layer on module level
worker: ["default from web-worker", "..."] // Customize the WebWorker handling for javascript files, "..." refers to the defaults.
}
}
]
}
}
If Rule.type
is an asset
then Rules.parser
option may be an object or a function that describes a condition whether to encode file contents to Base64 or emit it as a separate file into the output directory.
If Rule.type
is an asset
or asset/inline
then Rule.generator
option may be an object that describes the encoding of the module source or a function that encodes module's source by a custom algorithm.
See Asset Modules guide for additional information and use cases.
Rule.parser.dataUrlCondition
object = { maxSize number = 8096 }
function (source, { filename, module }) => boolean
If a module source size is less than maxSize
then module will be injected into the bundle as a Base64-encoded string, otherwise module file will be emitted into the output directory.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
parser: {
dataUrlCondition: {
maxSize: 4 * 1024
}
}
}
]
}
};
When a function is given, returning true
tells webpack to inject the module into the bundle as Base64-encoded string, otherwise module file will be emitted into the output directory.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
parser: {
dataUrlCondition: (source, { filename, module }) => {
const content = source.toString();
return content.includes('some marker');
}
}
}
]
}
};
Rule.generator.dataUrl
object = { encoding string = 'base64' | false, mimetype string = undefined | false }
function (content, { filename, module }) => string
When Rule.generator.dataUrl
is used as an object, you can configure two properties:
'base64'
, module source will be encoded using Base64 algorithm. Setting encoding
to false will disable encoding.webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
generator: {
dataUrl: {
encoding: 'base64',
mimetype: 'mimetype/png'
}
}
}
]
}
};
When used a a function, it executes for every module and must return a data URI string.
module.exports = {
//...
module: {
rules: [
{
//...
generator: {
dataUrl: content => {
const svgToMiniDataURI = require('mini-svg-data-uri');
if (typeof content !== 'string') {
content = content.toString();
}
return svgToMiniDataURI(content);
}
}
}
]
}
};
Rule.generator.filename
The same as output.assetModuleFilename
but for specific rule. Overrides output.assetModuleFilename
and works only with asset
and asset/resource
module types.
webpack.config.js
module.exports = {
//...
output: {
assetModuleFilename: 'images/[hash][ext][query]'
},
module: {
rules: [
{
test: /\.png/,
type: 'asset/resource'
},
{
test: /\.html/,
type: 'asset/resource',
generator: {
filename: 'static/[hash][ext]'
}
}
]
}
};
Rule.resource
A Condition
matched with the resource. See details in Rule
conditions.
Rule.resourceQuery
A Condition
matched with the resource query. This option is used to test against the query section of a request string (i.e. from the question mark onwards). If you were to import Foo from './foo.css?inline'
, the following condition would match:
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
test: /\\.css$/,
resourceQuery: /inline/,
use: 'url-loader'
}
]
}
};
Rule.parser.parse
function(input) => string | object
If Rule.type
is set to 'json'
then Rules.parser.parse
option may be a function that implements custom logic to parse module's source and convert it to a JavaScript object
. It may be useful to import toml
, yaml
and other non-JSON files as JSON, without specific loaders:
webpack.config.js
const toml = require('toml');
module.exports = {
//...
module: {
rules: [
{
test: /\.toml/,
type: 'json',
parser: {
parse: toml.parse
}
}
]
}
};
Rule.rules
An array of Rules
that is also used when the Rule matches.
Rule.sideEffects
bool
Indicate what parts of the module contain side effects. See Tree Shaking for details.
Rule.test
Include all modules that pass test assertion. If you supply a Rule.test
option, you cannot also supply a Rule.resource
. See Rule.resource
and Condition.test
for details.
Rule.type
string
Possible values: 'javascript/auto' | 'javascript/dynamic' | 'javascript/esm' | 'json' | 'webassembly/sync' | 'webassembly/async' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline'
Rule.type
sets the type for a matching module. This prevents defaultRules and their default importing behaviors from occurring. For example, if you want to load a .json
file through a custom loader, you'd need to set the type
to javascript/auto
to bypass webpack's built-in json importing. (See v4.0 changelog for more details)
webpack.config.js
module.exports = {
//...
module: {
rules: [
//...
{
test: /\\.json$/,
type: 'javascript/auto',
loader: 'custom-json-loader'
}
]
}
};
See Asset Modules guide for more about
asset*
type.
Rule.use
[UseEntry]
function(info)
[UseEntry]
Rule.use
can be an array of UseEntry which are applied to modules. Each entry specifies a loader to be used.
Passing a string (i.e. use: [ 'style-loader' ]
) is a shortcut to the loader property (i.e. use: [ { loader: 'style-loader '} ]
).
Loaders can be chained by passing multiple loaders, which will be applied from right to left (last to first configured).
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
//...
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
{
loader: 'less-loader',
options: {
noIeCompat: true
}
}
]
}
]
}
};
function(info)
Rule.use
can also be a function which receives the object argument describing the module being loaded, and must return an array of UseEntry
items.
The info
object parameter has the following fields:
compiler
: The current webpack compiler (can be undefined)issuer
: The path to the module that is importing the module being loadedrealResource
: Always the path to the module being loadedresource
: The path to the module being loaded, it is usually equal to realResource
except when the resource name is overwritten via !=!
in request stringThe same shortcut as an array can be used for the return value (i.e. use: [ 'style-loader' ]
).
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
use: (info) => ([
{
loader: 'custom-svg-loader'
},
{
loader: 'svgo-loader',
options: {
plugins: [{
cleanupIDs: { prefix: basename(info.resource) }
}]
}
}
])
}
]
}
};
See UseEntry for details.
Rule.resolve
Resolving can be configured on module level. See all available options on resolve configuration page. All applied resolve options get deeply merged with higher level resolve.
For example, let's imagine we have an entry in ./src/index.js
, ./src/footer/default.js
and a ./src/footer/overridden.js
to demonstrate the module level resolve.
./src/index.js
import footer from 'footer';
console.log(footer);
./src/footer/default.js
export default 'default footer';
./src/footer/overridden.js
export default 'overridden footer';
webpack.js.org
module.exports = {
resolve: {
alias: {
'footer': './footer/default.js'
}
}
};
When creating a bundle with this configuration, console.log(footer)
will output 'default footer'. Let's set Rule.resolve
for .js
files, and alias footer
to overridden.js
.
webpack.js.org
module.exports = {
resolve: {
alias: {
'footer': './footer/default.js'
}
},
module: {
rules: [
{
resolve: {
alias: {
'footer': './footer/overridden.js'
}
}
}
]
}
};
When creating a bundle with updated configuration, console.log(footer)
will output 'overridden footer'.
resolve.fullySpecified
boolean = true
When enabled, you should provide the file extension when import
ing a module in .mjs
files or any other .js
files when their nearest parent package.json
file contains a "type"
field with a value of "module"
, otherwise webpack would fail the compiling with a Module not found
error. And webpack won't resolve directories with filenames defined in the resolve.mainFiles
, you have to specify the filename yourself.
webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.m?js$/,
resolve: {
fullySpecified: false // disable the behaviour
}
}
]
}
};
Condition
Conditions can be one of these:
{ and: [Condition] }
: All Conditions must match.
{ or: [Condition] }
: Any Condition must match.
{ not: [Condition] }
: All Conditions must NOT match.
Example:
const path = require('path');
module.exports = {
//...
module: {
rules: [
{
test: /\\.css$/,
include: [
path.resolve(__dirname, 'app/styles'),
path.resolve(__dirname, 'vendor/styles')
]
}
]
}
};
UseEntry
object
function(info)
object
It must have a loader
property being a string. It is resolved relative to the configuration context
with the loader resolving options (resolveLoader).
It can have an options
property being a string or object. This value is passed to the loader, which should interpret it as loader options.
For compatibility a query
property is also possible, which is an alias for the options
property. Use the options
property instead.
Note that webpack needs to generate a unique module identifier from the resource and all loaders including options. It tries to do this with a JSON.stringify
of the options object. This is fine in 99.9% of cases, but may be not unique if you apply the same loaders with different options to the resource and the options have some stringified values.
It also breaks if the options object cannot be stringified (i.e. circular JSON). Because of this you can have a ident
property in the options object which is used as unique identifier.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
};
function(info)
A UseEntry
can also be a function which receives the object argument describing the module being loaded, and must return an options object. This can be used to vary the loader options on a per-module basis.
The info
object parameter has the following fields:
compiler
: The current webpack compiler (can be undefined)issuer
: The path to the module that is importing the module being loadedrealResource
: Always the path to the module being loadedresource
: The path to the module being loaded, it is usually equal to realResource
except when the resource name is overwritten via !=!
in request stringwebpack.config.js
module.exports = {
//...
module: {
rules: [
{
loader: 'file-loader',
options: {
outputPath: 'svgs'
}
},
(info) => ({
loader: 'svgo-loader',
options: {
plugins: [{
cleanupIDs: { prefix: basename(info.resource) }
}]
}
})
]
}
};
Avoid using these options as they are deprecated and will soon be removed.
These options describe the default settings for the context created when a dynamic dependency is encountered.
Example for an unknown
dynamic dependency: require
.
Example for an expr
dynamic dependency: require(expr)
.
Example for an wrapped
dynamic dependency: require('./templates/' + expr)
.
Here are the available options with their defaults:
webpack.config.js
module.exports = {
//...
module: {
exprContextCritical: true,
exprContextRecursive: true,
exprContextRegExp: false,
exprContextRequest: '.',
unknownContextCritical: true,
unknownContextRecursive: true,
unknownContextRegExp: false,
unknownContextRequest: '.',
wrappedContextCritical: false,
wrappedContextRecursive: true,
wrappedContextRegExp: /.*/,
strictExportPresence: false // since webpack 2.3.0
}
};
A few use cases:
wrappedContextCritical: true
.require(expr)
should include the whole directory: exprContextRegExp: /^\\.\\//
require('./templates/' + expr)
should not include subdirectories by default: wrappedContextRecursive: false
strictExportPresence
makes missing exports an error instead of warningwrappedContextRegExp: /\\.\\*/