Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is src/index.js
and will output the result in dist/main.js
minified and optimized for production.
Usually your projects will need to extend this functionality, for this you can create a webpack.config.js
file in the root folder and webpack will automatically use it.
All the available configuration options are specified below.
If for some reason you want to use different configuration file depending on certain situations you can change this via command line by using the --config
flag.
package.json
"scripts": {
"build": "webpack --config prod.config.js"
}
Click on the name of each option in the configuration code below to jump to the detailed documentation. Also note that the items with arrows can be expanded to show more examples and, in some cases, more advanced configuration.
webpack.config.js
const path = require('path');
module.exports = {
<mode "/configuration/mode">
<default>
mode: "production", // "production" | "development" | "none"
</default>
mode: "production", // enable many optimizations for production builds
mode: "development", // enabled useful tools for development
mode: "none", // no defaults
</mode>
// Chosen mode tells webpack to use its built-in optimizations accordingly.
<entry "/configuration/entry-context/#entry">
<default>
entry: "./app/entry", // string | object | array
</default>
entry: ["./app/entry1", "./app/entry2"],
entry: {
a: "./app/entry-a",
b: ["./app/entry-b1", "./app/entry-b2"]
},
entry: {
a: {
import: "./app/entry-a",
library: { type: "commonjs-module" },
dependOn: ["vendors"],
filename: "entries/a.js",
runtime: "dashboard",
chunkLoading: "jsonp",
wasmLoading: "fetch-streaming"
},
vendors: ["react", "react-dom"]
}
</entry>
// defaults to ./src
// Here the application starts executing
// and webpack starts bundling
<link "/configuration/output">
<default>
output: {
</default>
</link>
// options related to how webpack emits results
<path "/configuration/output/#outputpath">
<default>
path: path.resolve(__dirname, "dist"), // string (default)
</default>
</path>
// the target directory for all output files
// must be an absolute path (use the Node.js path module)
<filename "/configuration/output/#outputfilename">
<default>
filename: "[name].js", // string (default)
</default>
filename: "[contenthash].js", // for long term caching
</filename>
// the filename template for entry chunks
<publicPath "/configuration/output/#outputpublicpath">
<default>
publicPath: "/assets/", // string
</default>
publicPath: "auto", // determined automatically from script tag (default)
publicPath: "", // relative to HTML file
publicPath: "/", // relative to server root
publicPath: "https://cdn.example.com/", // absolute URL
</publicPath>
// the url to the output directory resolved relative to the HTML page
<library "/configuration/output/#outputlibrary">
<default>
library: { // There is also an old syntax for this available (click to show)
</default>
// Old syntax:
library: "MyLibrary", // string,
libraryTarget: "umd", // = library.type
auxiliaryComment: "comment", // = library.auxiliaryComment
libraryExport: "default", // = library.export
</library>
<libraryType "/configuration/output/#outputlibrarytype">
<default>
type: "umd", // universal module definition
</default>
type: "umd2", // universal module definition (but optional externals will use globals)
type: "commonjs-module", // exported with module.exports
type: "commonjs2", // old name for "commonjs-module"
type: "commonjs", // exported as properties to exports
type: "amd", // defined with AMD define() method
type: "amd-require", // defined with AMD require() method (can't have exports)
type: "system", // exported to System.js
type: "this", // property set on this
type: "var", // variable defined in root scope (default)
type: "assign", // blind assignment
type: "global", // property set to global object as specified in output.globalObject
type: "window", // property set to window object
type: "self", // property set to self object
type: "jsonp", // jsonp wrapper
type: "module", // EcmaScript Module (not implemented yet)
</libraryType>
// the type of the exported library
<libraryName "/configuration/output/#outputlibraryname">
<default>
name: "MyLibrary", // string | string[]
</default>
name: ["MyCompany", "MyLibrary"], // Some types support creating nested objects
name: undefined, // Some types support unnamed library (default)
</libraryName>
// the name of the exported library
<advancedLibrary "#">
<default>
/* Advanced output.library configuration (click to show) */
</default>
export: "default", // string | string[]
export: undefined, // expose the whole namespace object resp. module.exports value (default)
export: "named", // expose named exports
export: ["named", "property"], // expose nested properties
// the export of the entry module that should be exposed
auxiliaryComment: "comment",
auxiliaryComment: { amd: "comment", commonjs: "comment", commonjs2: "comment", root: "comment" },
// Add a comment in the UMD wrapper
umdNamedDefine: false,
// Use a named define() for the AMD part of the UMD wrapper
</advancedLibrary>
},
uniqueName: "my-application", // (defaults to package.json "name")
// unique name for this build to avoid conflicts with other builds in the same HTML
name: "my-config",
// name of the configuration, shown in output
<advancedOutput "#">
<default>
/* Advanced output configuration (click to show) */
</default>
chunkFilename: "[name].js",
chunkFilename: "[id].js",
chunkFilename: "[contenthash].js", // for long term caching
// the filename template for additional chunks
assetModuleFilename: "[hash][ext][query]", // string
// the filename template for asset modules
webassemblyModuleFilename: "[hash].module.wasm", // string
// the filename template for wasm modules
sourceMapFilename: "[file].map", // string
sourceMapFilename: "sourcemaps/[file].map", // string
// the filename template of the source map location
devtoolModuleFilenameTemplate: "webpack:///[resource-path]", // string
// the name template for modules in a devtool
devtoolFallbackModuleFilenameTemplate: "webpack:///[resource-path]?[hash]", // string
// the name template for modules in a devtool (used for conflicts)
crossOriginLoading: "use-credentials", // enum
crossOriginLoading: "anonymous",
crossOriginLoading: false,
// specifies how cross origin request are issued by the runtime
importFunctionName: "import", // string (default)
// expression that is called when using import()
// can be replaced to use polyfills
importMetaName: "import.meta", // string (default)
// expression that is used when using import.meta
// can be replaced to use polyfills
</advancedOutput>
<expertOutput "#">
<default>
/* Expert output configuration 1 (on own risk) */
</default>
pathinfo: true, // boolean
// include useful path info about modules, exports, requests, etc. into the generated code
charset: true, // string
// add charset attribute to injected script tags
chunkLoadTimeout: 120000, // number (default)
// timeout for loading chunks
compareBeforeEmit: true, // boolean (default)
// compare the generated asset with the asset on disk before writing to disk
strictModuleExceptionHandling: true, // boolean
// handle errors in module evaluation correctly, but for a performance cost
devtoolNamespace: "MyLibrary", // string
// prefix in the source names for devtools
// defaults to output.uniqueName
environment: {
// Properties about the environment
arrowFunction: true,
bigIntLiteral: true,
const: true,
destructuring: true,
dynamicImport: true,
forOf: true,
module: true
},
globalObject: "self", // string (default),
// expression that points to the global object
iife: true, // boolean (default)
// wrap the bundle in a IIFE for isolation
module: false, // boolean (default)
// generate a module type javascript file instead of a classic script
scriptType: "module"
// adds a type attribute to injected script tags
</expertOutput>
<expertOutputB "#">
<default>
/* Expert output configuration 2 (on own risk) */
</default>
chunkLoading: "jsonp" // "jsonp" | "import-scripts" | "require" | "async-node" | false
// method of loading chunks
chunkLoadingGlobal: "myWebpackJsonp", // string
// name of the global variable used to load chunks
enabledChunkLoadingTypes: ["jsonp"], // string[]
// the chunk loading methods that are available
enabledLibraryTypes: ["var"], // string[]
// the library types that are available
enabledWasmLoadingTypes: ["var"], // string[]
// the wasm loading methods that are available
chunkFormat: "array-push",
chunkFormat: "commonjs",
chunkFormat: false,
// the format of chunks
hotUpdateMainFilename: "[fullhash].hot-update.json", // string
// filename template for HMR manifest
hotUpdateChunkFilename: "[id].[fullhash].hot-update.js", // string
// filename template for HMR chunks
hotUpdateGlobal: "hmrUpdateFunction", // string
// the name of the global variable used to load hot update chunks
sourcePrefix: "\t", // string
// prefix module sources in bundle for better readability
// but breaks multi-line template strings
hashFunction: "md4", // string (default)
// hash function used in general
hashDigest: "hex", // string (default)
// hash digest type used
hashDigestLength: 20, // number (default)
// length of hashes
hashSalt: "salt", // string | Buffer
// an additional hash salt to fix hash related issues or change the hash in general
</expertOutputB>
},
module: {
// configuration regarding modules
rules: [
// rules for modules (configure loaders, parser options, etc.)
{
// Conditions:
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
exclude: [
path.resolve(__dirname, "app/demo-files")
],
// these are matching conditions, each accepting a regular expression or string
// test and include have the same behavior, both must be matched
// exclude must not be matched (takes preferrence over test and include)
// Best practices:
// - Use RegExp only in test and for filename matching
// - Use arrays of absolute paths in include and exclude to match the full path
// - Try to avoid exclude and prefer include
// Each condition can also receive an object with "and", "or" or "not" properties
// which are an array of conditions.
issuer: /\.css$/,
issuer: path.resolve(__dirname, "app"),
issuer: { and: [ /\.css$/, path.resolve(__dirname, "app") ] },
issuer: { or: [ /\.css$/, path.resolve(__dirname, "app") ] },
issuer: { not: [ /\.css$/ ] },
issuer: [ /\.css$/, path.resolve(__dirname, "app") ], // like "or"
// conditions for the issuer (the origin of the import)
<advancedConditions "#">
<default>
/* Advanced conditions (click to show) */
</default>
resource: /\.css$/,
// matches the resource of the module, behaves equal to "test" and "include"
compiler: /html-webpack-plugin/,
// matches the name of the child compilation
dependency: "esm", // import-style dependencies
dependency: "commonjs", // require-style dependencies
dependency: "amd", // AMD-style dependency
dependency: "wasm", // WebAssembly imports section
dependency: "url", // new URL(), url() and similar
dependency: "worker", // new Worker() and similar
dependency: "loader", // this.loadModule in loaders
// matches the type of dependency
descriptionData: { type: "module" },
// matches information from the package.json
mimetype: "text/javascript",
// matches the mimetype in DataUris
realResource: /\.css$/,
// matches the resource but ignores when resource was been renamed
resourceFragment: "#blah",
// matches the fragment part of the resource request
resourceQuery: "?blah"
// matches the query part of the resource request
</advancedConditions>
// Actions:
loader: "babel-loader",
// the loader which should be applied, it'll be resolved relative to the context
options: {
presets: ["es2015"]
},
// options for the loader
use: [
// apply multiple loaders and options instead
"htmllint-loader",
{
loader: "html-loader",
options: {
// ...
}
}
],
<moduleType "#">
<default>
type: "javascript/auto",
</default>
type: "javascript/auto", // JS with all features
type: "javascript/esm", // JS enforced to strict ESM
type: "javascript/dynamic", // JS enforced to non-ESM
type: "json", // JSON data
type: "webassembly/async", // WebAssembly as async module
type: "webassembly/sync", // WebAssembly as sync module
</moduleType>
// specifies the module type
<advancedActions "#">
<default>
/* Advanced actions (click to show) */
</default>
enforce: "pre",
enforce: "post",
// flags to apply these rules, even if they are overridden
generator: { /* ... */ },
// Options for the generator (depends on module type)
parser: { /* ... */ },
// Options for the parser (depends on module type)
resolve: { /* ... */ },
// Resolve options (same as "resolve" in configuration)
sideEffects: false, // boolean
// Overrides "sideEffects" from package.json
</advancedActions>
},
{
oneOf: [
// ... (rules)
]
// only use one of these nested rules
},
{
// ... (conditions)
rules: [
// ... (rules)
]
// use all of these nested rules (combine with conditions to be useful)
},
],
<advancedModule "#">
<default>
/* Advanced module configuration (click to show) */
</default>
noParse: [
/special-library\.js$/
],
// do not parse this module
unknownContextRequest: ".",
unknownContextRecursive: true,
unknownContextRegExp: /^\.\/.*$/,
unknownContextCritical: true,
exprContextRequest: ".",
exprContextRegExp: /^\.\/.*$/,
exprContextRecursive: true,
exprContextCritical: true,
wrappedContextRegExp: /.*/,
wrappedContextRecursive: true,
wrappedContextCritical: false,
// specifies default behavior for dynamic requests
</advancedModule>
},
resolve: {
// options for resolving module requests
// (does not apply to resolving of loaders)
<modules "/configuration/resolve/#resolvemodules">
<default>
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
</default>
modules: [ "node_modules" ],
// A filename (non-absolute) means this folder is looked up
// in all parent directories
modules: [ path.resolve(__dirname, "app") ],
// An absolute path means exactly this folder
</modules>
// directories where to look for modules (in order)
extensions: [".js", ".json", ".jsx", ".css"],
// extensions that are used
alias: {
// a list of module name aliases
// aliases are imported relative to the current context
"module": "new-module",
// alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"
"only-module$": "new-module",
// alias "only-module" -> "new-module", but not "only-module/path/file" -> "new-module/path/file"
"module": path.resolve(__dirname, "app/third/module.js"),
// alias "module" -> "./app/third/module.js" and "module/file" results in error
"module": path.resolve(__dirname, "app/third"),
// alias "module" -> "./app/third" and "module/file" -> "./app/third/file"
[path.resolve(__dirname, "app/module.js")]: path.resolve(__dirname, "app/alternative-module.js"),
// alias "./app/module.js" -> "./app/alternative-module.js"
},
<alias "/configuration/resolve/#resolvealias">
<default>
/* Alternative alias syntax (click to show) */
</default>
alias: [
{
name: "module",
// the old request
alias: "new-module",
// the new request
onlyModule: true
// if true only "module" is aliased
// if false "module/inner/path" is also aliased
}
],
</alias>
<advancedResolve "/configuration/resolve/">
<default>
/* Advanced resolve configuration (click to show) */
</default>
conditionNames: ["myCompanyCondition", "..."],
// conditions used for the "exports" and "imports" field in description file
roots: [path.resolve(__dirname, "app/root")],
// locations where to resolve server-relative requests (starting with "/")
// This behavior is only applied when the request doesn't resolve as absolute path
fallback: { "events": path.resolve(__dirname, "events.js") },
// Similar to alias, but only applied when the normal resolving fails
mainFields: ["main"],
// properties that are read from description file
// when a folder is requested
restrictions: [ /\.js$/, path.resolve(__dirname, "app") ],
// To successful resolve the result must match these criteria
cache: true, // boolean
// enable safe caching of resolving
// this is safe as it tracks and validates all resolving dependencies
unsafeCache: true,
unsafeCache: {},
// enables unsafe caching for resolved requests
// this is unsafe as there is no validation
// but performance improvement is really big
plugins: [
// ...
],
// additional plugins applied to the resolver
</advancedResolve>
<expertResolve "/configuration/resolve/">
<default>
/* Expert resolve configuration (click to show) */
</default>
symlinks: true, // (default)
// follow symlinks to new location
descriptionFiles: ["package.json"], // (default)
// files that are read for package description
aliasFields: ["browser"],
// properties that are read from description file
// to alias requests in this package
exportsFields: ["exports"], // (default)
// fields in description file that are used for external module request
importsFields: ["imports"], // (default)
// fields in description file that are used for internal request
mainFiles: ["index"],
// files that are used when resolving in a directory and no mainField applies
fullySpecified: true, // boolean
// Input request is already full specified (it includes filename and extension)
// Module requests are still resolved as usual
preferRelative: true, // boolean
// Try to resolve module requests also a relative request
enforceExtension: false,
// if true request must not include an extension
// if false request may already include an extension
cachePredicate: ({ path, request }) => true,
// predicate function which selects requests for caching
cacheWithContext: false, // (default)
// include context information in cache key
// This must be set to true when custom plugins resolve depending on
// those information
useSyncFileSystemCalls: false, // (default)
// use sync fs calls instead of async fs calls
byDependency: { commonjs: { extensions: [".js", "..."] } },
// change resolving depending on issuer dependency
</expertResolve>
},
performance: {
<hints "/configuration/performance/#performancehints">
<default>
hints: "warning", // enum
</default>
hints: "error", // emit errors for perf hints
hints: false, // turn off perf hints
</hints>
maxAssetSize: 200000, // int (in bytes),
maxEntrypointSize: 400000, // int (in bytes)
assetFilter: function(assetFilename) {
// Function predicate that provides asset filenames
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
}
},
<devtool "/configuration/devtool">
<default>
devtool: "source-map", // enum
</default>
devtool: "inline-source-map", // inlines SourceMap into original file
devtool: "hidden-source-map", // SourceMap without reference in original file
devtool: "eval-source-map", // inlines SourceMap per module
devtool: "cheap-source-map", // cheap-variant of SourceMap without module mappings
devtool: "cheap-module-source-map", // cheap-variant of SourceMap with module mappings
devtool: "eval-cheap-module-source-map", // like above but per module
devtool: "eval", // no SourceMap, but named modules. Fastest at the expense of detail.
devtool: false, // no SourceMap
</devtool>
// enhance debugging by adding meta info for the browser devtools
// source-map most detailed at the expense of build speed.
context: __dirname, // string (absolute path!)
// the home directory for webpack
// the entry and module.rules.loader option
// is resolved relative to this directory
<target "/configuration/target">
<default>
target: "web", // enum
</default>
target: "browserslist", // use browserslist
target: "browserslist:modern", // use browserslist "modern" preset
target: "browserslist:Chrome >= 43", // use browserslist query
target: `browserslist:${path.resolve(__dirname, "browserslist.json")}`,
target: `browserslist:${path.resolve(__dirname, "browserslist.json")}:modern`,
target: "webworker", // WebWorker
target: "node", // Node.js via require
target: "node10.13", // Node.js via require
target: "async-node10.13", // Node.js via fs and vm
target: "nwjs0.43", // nw.js
target: "electron11.0-main", // electron, main process
target: "electron11-renderer", // electron, renderer process
target: "electron-preload", // electron, preload script
target: ["web", "es5"], // combining targets
target: ["web", "es2020"],
target: false, // custom target, via plugin
</target>
// the environment in which the bundle should run
// changes chunk loading behavior, available external modules
// and generated code style
<externals "/configuration/externals">
<default>
externals: ["react", /^@angular/],
</default>
externals: "react", // string (exact match)
externals: /^[a-z\-]+($|\/)/, // Regex
externals: { // object
angular: "this angular", // this["angular"]
react: { // UMD
commonjs: "react",
commonjs2: "react",
amd: "react",
root: "React"
}
},
externals: ({ context, request }, callback) => { /* ... */ callback(null, "commonjs " + request); }
</externals>
// Don't follow/bundle these modules, but request them at runtime from the environment
<externalsType "/configuration/externals">
<default>
externalsType: "var", // (defaults to output.library.type)
</default>
externalsType: "this", // this["EXTERNAL"]
externalsType: "window", // window["EXTERNAL"]
externalsType: "self", // self["EXTERNAL"]
externalsType: "global", // property from output.globalObject
externalsType: "commonjs", // require("EXTERNAL")
externalsType: "amd", // define(["EXTERNAL"], ...), only with AMD library
externalsType: "umd", // only with UMD library
externalsType: "system", // only with System.js library
externalsType: "jsonp", // only with jsonp library
externalsType: "import", // import("EXTERNAL")
externalsType: "module", // import X from "EXTERNAL"
externalsType: "var", // EXTERNAL (name is an expression)
externalsType: "promise", // await EXTERNAL (name is an expression giving a Promise)
</externalsType>
// Type of externals, when not specified inline in externals
<externalsPresets "#">
<default>
externalsPresets: { /* ... */ },
</default>
externalsPresets: {
electron: true,
electronMain: true,
electronPreload: true,
electronRenderer: true,
node: true,
nwjs: true,
web: true,
webAsync: true,
}
</externalsPresets>
// presets of externals
<ignoreWarnings "#">
<default>
ignoreWarnings: [/warning/],
</default>
ignoreWarnings: [
/warning/,
{
file: /asset/,
module: /module/,
message: /warning/,
},
(warning, compilation) => true
],
</ignoreWarnings>
<stats "/configuration/stats">
<default>
stats: "errors-only",
</default>
stats: "verbose", // nearly all information
stats: "detailed", // much information
stats: "minimal", // summarized information
stats: "errors-warnings", // only errors and warnings
stats: "errors-only", // only errors
stats: "summary", // only one line summary
stats: "none", // none at all
</stats>
stats: {
// lets you precisely control what bundle information gets displayed
<preset "/configuration/stats/#stats-presets">
<default>
preset: "errors-only",
</default>
preset: "verbose", // nearly all information
preset: "detailed", // much information
preset: "minimal", // summarized information
preset: "errors-warnings", // only errors and warnings
preset: "errors-only", // only errors
preset: "summary", // only one line summary
preset: "none", // none at all
</preset>
// A stats preset
<advancedGlobal "/configuration/stats/">
<default>
/* Advanced global settings (click to show) */
</default>
all: false,
// switch all flags on or off
colors: true,
// switch colors on and off
context: __dirname,
// all paths will be relative to this directory
ids: true,
// include module and chunk ids in the output
</advancedGlobal>
env: true,
// include value of --env in the output
outputPath: true,
// include absolute output path in the output
publicPath: true,
// include public path in the output
assets: true,
// show list of assets in output
<advancedAssets "/configuration/stats/">
<default>
/* Advanced assets settings (click to show) */
</default>
assetsSort: "size",
// sorting of assets
assetsSpace: 50,
// number of asset lines to display
cachedAssets: false,
// show assets that are caching in output
excludeAssets: /\.png$/,
// hide some assets
groupAssetsByPath: true,
// group assets by their path in the output directory
groupAssetsByExtension: true,
// group assets by their extension
groupAssetsByEmitStatus: true,
// group assets depending if they are cached, emitted or compared
groupAssetsByChunk: true,
// group assets by how they relate to chunks
groupAssetsByInfo: true,
// group assets by meta information like immutable, development, etc.
relatedAssets: true,
// show assets that are related to other assets, like SourceMaps, compressed version, etc.
performance: true,
// show performance hints next to assets and modules
</advancedAssets>
entrypoints: true,
// show entrypoints list
chunkGroups: true,
// show named chunk group list
<advancedChunkGroups "/configuration/stats/">
<default>
/* Advanced chunk group settings (click to show) */
</default>
chunkGroupAuxiliary: true,
// show auxiliary assets for entrypoints/chunk groups
chunkGroupChildren
// show child chunk groups for entrypoints/chunk groups
chunkGroupMaxAssets: 5,
// collapse chunk group assets lists when this limit has been reached
</advancedChunkGroups>
chunks: true,
// show list of chunks in output
<advancedChunks "/configuration/stats/">
<default>
/* Advanced chunk group settings (click to show) */
</default>
chunksSort: "size",
// sort chunks list
chunkModules: true,
// show modules contained in each chunk
chunkOrigins: true,
// show the origin of a chunk (why was this chunk created)
chunkRelations: true,
// show relations to other chunks (parents, children, sibilings)
dependentModules: true,
// show modules that are dependencies of other modules in that chunk
</advancedChunks>
modules: true,
// show list of modules in output
<advancedModules "/configuration/stats/">
<default>
/* Advanced module settings (click to show) */
</default>
modulesSpace: 50,
// number of modules lines to display
nestedModules: true,
// show nested modules (when concatenated)
cachedModules: true,
// show modules that were cached
orphanModules: true,
// show modules that are not referenced in optimized graph anymore
excludeModules: /\.css$/,
// hide some modules
reasons: true,
// show the reasons why modules are included
source: true,
// include the Source Code of modules (only in JSON)
</advancedModules>
<expertModules "/configuration/stats/">
<default>
/* Expert module settings (click to show) */
</default>
modulesSort: "size",
// sort modules list
groupModulesByPath: true,
// group modules by their resource path
groupModulesByExtension: true
// group modules by their extension
groupModulesByAttributes: true
// group modules by attributes like if the have errors/warnings/assets
// or are optional
groupModulesByCacheStatus: true,
// group modules depending if they are built, code was generated or if
// they are cacheable in general
depth: true,
// show depth in the module graph of modules
moduleAssets: true,
// show assets emitted by modules in module list
runtimeModules: true,
// show runtime modules in the modules list
</expertModules>
<advancedStatsOptimization "/configuration/stats/">
<default>
/* Advanced optimization settings (click to show) */
</default>
providedExports: true,
// show exports provided by modules
usedExports: true,
// show which exports are used by modules
optimizationBailout: true,
// show information why optimizations bailed out for modules
</advancedStatsOptimization>
children: true,
// show stats for child compilations
logging: true,
// show logging in output
loggingDebug: /webpack/,
// show debug type logging for some loggers
loggingTrace: true,
// show stack traces for warnings and errors in logging output
warnings: true,
// show warnings
errors: true,
// show errors
errorDetails: true,
// show details for errors
errorStack: true,
// show internal stack trace for errors
moduleTrace: true,
// show module trace for errors
// (why was causing module referenced)
builtAt: true,
// show timestamp in summary
errorsCount: true,
// show errors count in summary
warningsCount: true,
// show warnings count in summary
timings: true,
// show build timing in summary
version: true,
// show webpack version in summary
hash: true,
// show build hash in summary
},
devServer: {
proxy: { // proxy URLs to backend development server
'/api': 'http://localhost:3000'
},
contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
compress: true, // enable gzip compression
historyApiFallback: true, // true for index.html upon 404, object for multiple paths
hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
https: false, // true for self-signed, object for cert authority
noInfo: true, // only errors & warns on hot reload
// ...
},
experiments: {
asyncWebAssembly: true,
// WebAssembly as async module (Proposal)
syncWebAssembly: true,
// WebAssembly as sync module (deprecated)
outputModule: true,
// Allow to output ESM
topLevelAwait: true,
// Allow to use await on module evaluation (Proposal)
},
plugins: [
// ...
],
// list of additional plugins
optimization: {
chunkIds: "size",
// method of generating ids for chunks
moduleIds: "size",
// method of generating ids for modules
mangleExports: "size",
// rename export names to shorter names
minimize: true,
// minimize the output files
minimizer: [new CssMinimizer(), "..."],
// minimizers to use for the output files
<advancedOptimization "#">
<default>
/* Advanced optimizations (click to show) */
</default>
concatenateModules: true,
// concatenate multiple modules into a single one
emitOnErrors: true,
// emit output files even if there are build errors
flagIncludedChunks: true,
// avoid downloading a chunk if it's fully contained in
// an already loaded chunk
innerGraph: true,
// determine references without modules between symbols
mergeDuplicateChunks: true,
// merge chunks if they are equal
nodeEnv: "production",
// value of process.env.NODE_ENV inside of modules
portableRecords: true,
// use relative paths in records
providedExports: true,
// determine which exports are exposed by modules
usedExports: true,
// determine which exports are used by modules and
// remove the unused ones
realContentHash: true,
// caculcate a contenthash for assets based on the content
removeAvailableModules: true,
// run extra pass to determine modules that are already in
// parent chunks and remove them
removeEmptyChunks: true,
// remove chunks that are empty
runtimeChunk: "single",
// change placement of runtime code
sideEffects: true,
// skip modules that are side effect free when using reexports
</advancedOptimization>
splitChunks: {
cacheGroups: {
"my-name": {
// define groups of modules with specific
// caching behavior
test: /\.sass$/,
type: "css/mini-extract",
<cacheGroupAdvancedSelectors "#">
<default>
/* Advanced selectors (click to show) */
</default>
chunks: "async",
minChunks: 1,
enforceSizeThreshold: 100000,
minSize: 0,
minRemainingSize: 0,
usedExports: true,
maxAsyncRequests: 30,
maxInitialRequests: 30,
</cacheGroupAdvancedSelectors>
<cacheGroupAdvancedEffects "#">
<default>
/* Advanced effects (click to show) */
</default>
maxAsyncSize: 200000,
maxInitialSize: 100000,
maxSize: 200000,
filename: "my-name-[contenthash].js",
idHint: "my-name",
name: false,
hidePathInfo: true,
automaticNameDelimiter: "-",
</cacheGroupAdvancedEffects>
}
},
<fallbackCacheGroup "#">
<default>
fallbackCacheGroup: { /* Advanced (click to show) */ }
</default>
fallbackCacheGroup: {
automaticNameDelimiter: "-"
minSize: 20000,
maxAsyncSize: 200000,
maxInitialSize: 100000,
maxSize: 200000,
},
</fallbackCacheGroup>
<advancedSelectors "#">
<default>
/* Advanced selectors (click to show) */
</default>
chunks: "all",
// select which chunks should be optimized
usedExports: true,
// treat modules as equal only when used exports are equal
minChunks: 1,
// minimum number of chunks a module must be in
enforceSizeThreshold: 100000,
// ignore when following criterias when size of modules
// is above this threshold
minSize: 20000,
// size of modules must be above this threshold
minRemainingSize: 20000,
// when modules are removed from a single chunk
// the size of the modules that are remaining
// must be above this threshold
maxAsyncRequests: 30,
maxInitialRequests: 30,
// number of parallel requests for a single on demand loading
// resp. entrypoint but be above this threshold
</advancedSelectors>
<advancedEffects "#">
<default>
/* Advanced effects (click to show) */
</default>
maxAsyncSize: 200000,
maxInitialSize: 100000,
maxSize: 200000,
// when size of modules in the new chunk is above this
// threshold, split it further
filename: "[contenthash].js",
// give the new chunk a different filename
name: false, // false | string | (module, chunks, key) => string
// give the new chunk a different name
// when an existing name is used, chunks are merged
// non-splitChunks chunks can only be selected, when they are
// a parent or sibling chunk of all selected modules
hidePathInfo: true,
// hide path info when splitting via "maxSize"
automaticNameDelimiter: "-",
// use this separator to separate original name from path info
// when splitting via "maxSize"
</advancedEffects>
<expert "#">
<default>
/* Expert settings (click to show) */
</default>
defaultSizeTypes: ["javascript", "..."]
// when using numbers for sizes measure these size types
// minSize: { javascript: 10000 } allows to be more specific
</expert>
}
},
<advanced "#">
<default>
/* Advanced configuration (click to show) */
</default>
loader: { /* ... */ },
// add custom API or properties to loader context
resolveLoader: { /* same as resolve */ }
// separate resolve options for loaders
node: {
// Polyfills and mocks to run Node.js-
// environment code in non-Node environments.
global: true, // boolean
// replace "global" with the output.globalObject
__filename: "mock", // boolean | "mock" | "eval-only"
__dirname: "mock", // boolean | "mock" | "eval-only"
// true: includes the real path
// "mock": includes a fake path
// "eval-only": only defines it at compile-time
// false: disables all handling
},
recordsPath: path.resolve(__dirname, "build/records.json"),
recordsInputPath: path.resolve(__dirname, "build/records.json"),
recordsOutputPath: path.resolve(__dirname, "build/records.json"),
// store ids into a file to make the build even more deterministic
</advanced>
<advancedCaching "#">
<default>
/* Advanced caching configuration (click to show) */
</default>
cache: false, // boolean
// disable/enable caching
snapshot: {
managedPaths: [ path.resolve(__dirname, "node_modules") ],
// paths that are snapshot using only package.json name and version
immutablePaths: [ path.resolve(__dirname, ".yarn/cache") ],
// paths that doesn't need to be snapshot as they are immutable
module: { timestamp: true, hash: true },
resolve: { timestamp: true, hash: false },
resolveBuildDependencies: { timestamp: true, hash: false },
buildDependencies: { timestamp: true, hash: true },
// snapshot method for different operations
},
watch: true, // boolean
// enables watching
watchOptions: {
aggregateTimeout: 1000, // in ms
// aggregates multiple changes to a single rebuild
poll: true,
poll: 500, // intervall in ms
// enables polling mode for watching
// must be used on filesystems that doesn't notify on change
// i. e. nfs shares
},
</advancedCaching>
<advancedBuild "#">
<default>
/* Advanced build configuration (click to show) */
</default>
infrastructureLogging: {
level: "none",
level: "error",
level: "warn",
level: "info", // (default)
level: "log",
level: "verbose",
debug: true,
debug: /webpack/,
debug: [ "MyPlugin", /webpack/ ]
},
parallelism: 1, // number
// limit the number of parallel processed modules
profile: true, // boolean
// capture timing information
bail: true, //boolean
// fail out on the first error instead of tolerating it.
dependencies: ["name"],
// When using an array of configs this can be used to reference other
// configs and let this config run after the other config at initial build
</advancedBuild>
}
Use webpack-cli's init
command to rapidly generate webpack configuration file for your project requirements, it will ask you a couple of questions before creating a configuration file.
npx webpack-cli init
npx might prompt you to install @webpack-cli/init
if it is not yet installed in the project or globally. You might also get additional packages installed to your project depending on the choices you've made during the configuration generation.
npx webpack-cli init
βΉ INFO For more information and a detailed description of each question, have a look at https://github.com/webpack/webpack-cli/blob/master/INIT.md
βΉ INFO Alternatively, run `webpack(-cli) --help` for usage info.
? Will your application have multiple bundles? No
? Which module will be the first to enter the application? [default: ./src/index]
? Which folder will your generated bundles be in? [default: dist]:
? Will you be using ES2015? Yes
? Will you use one of the below CSS solutions? No
+ babel-plugin-syntax-dynamic-import@6.18.0
+ uglifyjs-webpack-plugin@2.0.1
+ webpack-cli@3.2.3
+ @babel/core@7.2.2
+ babel-loader@8.0.4
+ @babel/preset-env@7.1.0
+ webpack@4.29.3
added 124 packages from 39 contributors, updated 4 packages and audited 25221 packages in 7.463s
found 0 vulnerabilities
Congratulations! Your new webpack configuration file has been created!
createapp.dev - create a webpack configuration in your browser is an online tool for creating custom webpack configuration. It allows you to select various features that will be combined and added to resulting configuration file. Also, it generates an example project based on provided webpack configuration that you can review in your browser and download.
webpack accepts configuration files written in multiple programming and data languages. The list of supported file extensions can be found at the node-interpret package. Using node-interpret, webpack can handle many different types of configuration files.
To write the webpack configuration in TypeScript, you would first install the necessary dependencies, i.e., TypeScript and the relevant type definitions from the DefinitelyTyped project:
npm install --save-dev typescript ts-node @types/node @types/webpack
# and, if using webpack-dev-server
npm install --save-dev @types/webpack-dev-server
and then proceed to write your configuration:
webpack.config.ts
import * as path from 'path';
import * as webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
export default config;
Above sample assumes version >= 2.7 or newer of TypeScript is used with the new esModuleInterop
and allowSyntheticDefaultImports
compiler options in your tsconfig.json
file.
Note that you'll also need to check your tsconfig.json
file. If the module
in compilerOptions
in tsconfig.json
is commonjs
, the setting is complete, else webpack will fail with an error. This occurs because ts-node
does not support any module syntax other than commonjs
.
There are two solutions to this issue:
tsconfig.json
.tsconfig-paths
.The first option is to open your tsconfig.json
file and look for compilerOptions
. Set target
to "ES5"
and module
to "CommonJS"
(or completely remove the module
option).
The second option is to install the tsconfig-paths
package:
npm install --save-dev tsconfig-paths
And create a separate TypeScript configuration specifically for your webpack configs:
tsconfig-for-webpack-config.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"esModuleInterop": true
}
}
Then set the environment variable process.env.TS_NODE_PROJECT
provided by tsconfig-paths
like so:
package.json
{
"scripts": {
"build": "cross-env TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack"
}
}
Similarly, to use CoffeeScript, you would first install the necessary dependencies:
npm install --save-dev coffeescript
and then proceed to write your configuration:
webpack.config.coffee
HtmlWebpackPlugin = require('html-webpack-plugin')
webpack = require('webpack')
path = require('path')
config =
mode: 'production'
entry: './path/to/my/entry/file.js'
output:
path: path.resolve(__dirname, 'dist')
filename: 'my-first-webpack.bundle.js'
module: rules: [ {
test: /\.(js|jsx)$/
use: 'babel-loader'
} ]
plugins: [
new HtmlWebpackPlugin(template: './src/index.html')
]
module.exports = config
In the example below JSX (React JavaScript Markup) and Babel are used to create a JSON Configuration that webpack can understand.
Courtesy of Jason Miller
First install the necessary dependencies:
npm install --save-dev babel-register jsxobj babel-preset-es2015
.babelrc
{
"presets": [ "es2015" ]
}
webpack.config.babel.js
import jsxobj from 'jsxobj';
// example of an imported plugin
const CustomPlugin = config => ({
...config,
name: 'custom-plugin'
});
export default (
<webpack target="web" watch mode="production">
<entry path="src/index.js" />
<resolve>
<alias {...{
react: 'preact-compat',
'react-dom': 'preact-compat'
}} />
</resolve>
<plugins>
<CustomPlugin foo="bar" />
</plugins>
</webpack>
);
Besides exporting a single configuration object, there are a few more ways that cover other needs as well.
Eventually you will find the need to disambiguate in your webpack.config.js
between development and production builds. You have (at least) two options:
One option is to export a function from your webpack configuration instead of exporting an object. The function will be invoked with two arguments:
argv
) as the second parameter. This describes the options passed to webpack, with keys such as output-filename
and optimize-minimize
.-module.exports = {
+module.exports = function(env, argv) {
+ return {
+ mode: env.production ? 'production' : 'development',
+ devtool: env.production ? 'source-map' : 'eval',
plugins: [
new TerserPlugin({
terserOptions: {
+ compress: argv['optimize-minimize'] // only if -p or --optimize-minimize were passed
}
})
]
+ };
};
webpack will run the function exported by the configuration file and wait for a Promise to be returned. Handy when you need to asynchronously load configuration variables.
module.exports = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
entry: './app.js',
/* ... */
});
}, 5000);
});
};
Instead of exporting a single configuration object/function, you may export multiple configurations (multiple functions are supported since webpack 3.1.0). When running webpack, all configurations are built. For instance, this is useful for bundling a library for multiple targets such as AMD and CommonJS:
module.exports = [{
output: {
filename: './dist-amd.js',
libraryTarget: 'amd'
},
name: 'amd',
entry: './app.js',
mode: 'production',
}, {
output: {
filename: './dist-commonjs.js',
libraryTarget: 'commonjs'
},
name: 'commonjs',
entry: './app.js',
mode: 'production',
}];
The entry object is where webpack looks to start building the bundle. The context is an absolute string to the directory that contains the entry files.
context
string
The base directory, an absolute path, for resolving entry points and loaders from configuration.
const path = require('path');
module.exports = {
//...
context: path.resolve(__dirname, 'app')
};
By default the current directory is used, but it's recommended to pass a value in your configuration. This makes your configuration independent from CWD (current working directory).
entry
string
[string]
object = { <key> string | [string] | object = { import string | [string], dependOn string | [string], filename string, layer string }}
(function() => string | [string] | object = { <key> string | [string] } | object = { import string | [string], dependOn string | [string], filename string })
The point or points where to start the application bundling process. If an array is passed then all items will be processed.
A dynamically loaded module is not an entry point.
Simple rule: one entry point per HTML page. SPA: one entry point, MPA: multiple entry points.
module.exports = {
//...
entry: {
home: './home.js',
about: './about.js',
contact: './contact.js'
}
};
If a string or array of strings is passed, the chunk is named main
. If an object is passed, each key is the name of a chunk, and the value describes the entry point for the chunk.
If an object is passed the value might be a string, array of strings or a descriptor:
module.exports = {
//...
entry: {
home: './home.js',
shared: ['react', 'react-dom', 'redux', 'react-redux'],
catalog: {
import: './catalog.js',
filename: 'pages/catalog.js',
dependOn:'shared'
},
personal: {
import: './personal.js',
filename: 'pages/personal.js',
dependOn: 'shared',
chunkLoading: 'jsonp',
layer: 'name of layer', // set the layer for an entry point
}
}
};
Descriptor syntax might be used to pass additional options to an entry point.
By default, the output filename for the entry chunk is extracted from output.filename
but you can specify a custom output filename for a specific entry:
module.exports = {
//...
entry: {
app: './app.js',
home: { import: './contact.js', filename: 'pages/[name][ext]' },
about: { import: './about.js', filename: 'pages/[name][ext]' }
}
};
Descriptor syntax was used here to pass filename
-option to the specific entry points.
By default, every entry chunk stores all the modules that it uses. With dependOn
option you can share the modules from one entry chunk to another:
module.exports = {
//...
entry: {
app: { import: './app.js', dependOn: 'react-vendors' },
'react-vendors': ['react', 'react-dom', 'prop-types']
}
};
The app
chunk will not contain the modules that react-vendors
has.
dependOn
option can also accept an array of strings:
module.exports = {
//...
entry: {
moment: { import: 'moment-mini', runtime: 'runtime' },
reactvendors: { import: ['react', 'react-dom'], runtime: 'runtime' },
testapp: {
import: './wwwroot/component/TestApp.tsx',
dependOn: ['reactvendors', 'moment'],
},
},
};
Also, you can specify multiple files per entry using an array:
module.exports = {
//...
entry: {
app: { import: ['./app.js', './app2.js'], dependOn: 'react-vendors' },
'react-vendors': ['react', 'react-dom', 'prop-types']
}
};
If a function is passed then it will be invoked on every make event.
Note that the make event triggers when webpack starts and for every invalidation when watching for file changes.
module.exports = {
//...
entry: () => './demo'
};
or
module.exports = {
//...
entry: () => new Promise((resolve) => resolve(['./demo', './demo2']))
};
For example: you can use dynamic entries to get the actual entries from an external source (remote server, file system content or database):
webpack.config.js
module.exports = {
entry() {
return fetchPathsFromSomeExternalSource(); // returns a promise that will be resolved with something like ['src/main-layout.js', 'src/admin-layout.js']
}
};
When combining with the output.library
option: If an array is passed only the last item is exported.
Providing the mode
configuration option tells webpack to use its built-in optimizations accordingly.
string = 'production': 'none' | 'development' | 'production'
Provide the mode
option in the config:
module.exports = {
mode: 'development'
};
or pass it as a CLI argument:
webpack --mode=development
The following string values are supported:
Option | Description |
---|---|
development | Sets process.env.NODE_ENV on DefinePlugin to value development . Enables useful names for modules and chunks. |
production | Sets process.env.NODE_ENV on DefinePlugin to value production . Enables deterministic mangled names for modules and chunks, FlagDependencyUsagePlugin , FlagIncludedChunksPlugin , ModuleConcatenationPlugin , NoEmitOnErrorsPlugin and TerserPlugin . |
none | Opts out of any default optimization options |
If not set, webpack sets production
as the default value for mode
.
// webpack.development.config.js
module.exports = {
+ mode: 'development'
- devtool: 'eval',
- cache: true,
- performance: {
- hints: false
- },
- output: {
- pathinfo: true
- },
- optimization: {
- moduleIds: 'named',
- chunkIds: 'named',
- mangleExports: false,
- nodeEnv: 'development',
- flagIncludedChunks: false,
- occurrenceOrder: false,
- concatenateModules: false,
- splitChunks: {
- hidePathInfo: false,
- minSize: 10000,
- maxAsyncRequests: Infinity,
- maxInitialRequests: Infinity,
- },
- emitOnErrors: true,
- checkWasmTypes: false,
- minimize: false,
- removeAvailableModules: false
- },
- plugins: [
- new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }),
- ]
}
// webpack.production.config.js
module.exports = {
+ mode: 'production',
- performance: {
- hints: 'warning'
- },
- output: {
- pathinfo: false
- },
- optimization: {
- moduleIds: 'deterministic',
- chunkIds: 'deterministic',
- mangleExports: 'deterministic',
- nodeEnv: 'production',
- flagIncludedChunks: true,
- occurrenceOrder: true,
- concatenateModules: true,
- splitChunks: {
- hidePathInfo: true,
- minSize: 30000,
- maxAsyncRequests: 5,
- maxInitialRequests: 3,
- },
- emitOnErrors: false,
- checkWasmTypes: true,
- minimize: true,
- },
- plugins: [
- new TerserPlugin(/* ... */),
- new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
- new webpack.optimize.ModuleConcatenationPlugin(),
- new webpack.NoEmitOnErrorsPlugin()
- ]
}
// webpack.custom.config.js
module.exports = {
+ mode: 'none',
- performance: {
- hints: false
- },
- optimization: {
- flagIncludedChunks: false,
- occurrenceOrder: false,
- concatenateModules: false,
- splitChunks: {
- hidePathInfo: false,
- minSize: 10000,
- maxAsyncRequests: Infinity,
- maxInitialRequests: Infinity,
- },
- emitOnErrors: true,
- checkWasmTypes: false,
- minimize: false,
- },
- plugins: []
}
If you want to change the behavior according to the mode variable inside the webpack.config.js, you have to export a function instead of an object:
var config = {
entry: './app.js'
//...
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
config.devtool = 'source-map';
}
if (argv.mode === 'production') {
//...
}
return config;
};
The top-level output
key contains set of options instructing webpack on how and where it should output your bundles, assets and anything else you bundle or load with webpack.
output.auxiliaryComment
string
object
When used in tandem with output.library
and output.libraryTarget
, this option allows users to insert comments within the export wrapper. To insert the same comment for each libraryTarget
type, set auxiliaryComment
to a string:
webpack.config.js
module.exports = {
//...
output: {
library: 'someLibName',
libraryTarget: 'umd',
filename: 'someLibName.js',
auxiliaryComment: 'Test Comment'
}
};
which will yield the following:
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__) {
// ...
});
For fine-grained control over each libraryTarget
comment, pass an object:
webpack.config.js
module.exports = {
//...
output: {
//...
auxiliaryComment: {
root: 'Root Comment',
commonjs: 'CommonJS Comment',
commonjs2: 'CommonJS2 Comment',
amd: 'AMD Comment'
}
}
};
output.charset
boolean = true
Tells webpack to add charset="utf-8"
to the HTML <script>
tag.
output.chunkFilename
string = '[id].js'
function (pathData, assetInfo) => string
This option determines the name of non-initial chunk files. See output.filename
option for details on the possible values.
Note that these filenames need to be generated at runtime to send the requests for chunks. Because of this, placeholders like [name]
and [chunkhash]
need to add a mapping from chunk id to placeholder value to the output bundle with the webpack runtime. This increases the size and may invalidate the bundle when placeholder value for any chunk changes.
By default [id].js
is used or a value inferred from output.filename
([name]
is replaced with [id]
or [id].
is prepended).
webpack.config.js
module.exports = {
//...
output: {
//...
chunkFilename: '[id].js'
}
};
Usage as a function:
webpack.config.js
module.exports = {
//...
output: {
chunkFilename: (pathData) => {
return pathData.chunk.name === 'main' ? '[name].js': '[name]/[name].js';
},
}
};
output.chunkLoadTimeout
number = 120000
Number of milliseconds before chunk request expires. This option is supported since webpack 2.6.0.
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoadTimeout: 30000
}
};
output.chunkLoadingGlobal
string = 'webpackChunkwebpack'
The global variable used by webpack for loading of chunks.
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoadingGlobal: 'myCustomFunc'
}
};
output.chunkLoading
false
string: 'jsonp' | 'import-scripts' | 'require' | 'async-node' | <any string>
The method to load chunks (methods included by default are 'jsonp' (web), 'importScripts' (WebWorker), 'require' (sync node.js), 'async-node' (async node.js), but others might be added by plugins).
webpack.config.js
module.exports = {
//...
output: {
//...
chunkLoading: 'async-node'
}
};
output.chunkFormat
false
string: 'array-push' | 'commonjs' | <any string>
The format of chunks (formats included by default are 'array-push' (web/WebWorker), 'commonjs' (node.js), but others might be added by plugins).
webpack.config.js
module.exports = {
//...
output: {
//...
chunkFormat: 'commonjs'
}
};
output.enabledChunkLoadingTypes
[string: 'jsonp' | 'import-scripts' | 'require' | 'async-node' | <any string>]
List of chunk loading types enabled for use by entry points. Will be automatically filled by webpack. Only needed when using a function as entry option and returning chunkLoading option from there.
webpack.config.js
module.exports = {
//...
output: {
//...
enabledChunkLoadingTypes: ['jsonp', 'require']
}
};
output.crossOriginLoading
boolean = false
string: 'anonymous' | 'use-credentials'
Tells webpack to enable cross-origin loading of chunks. Only takes effect when target
is set to 'web'
, which uses JSONP for loading on-demand chunks, by adding script tags.
'anonymous'
- Enable cross-origin loading without credentials'use-credentials'
- Enable cross-origin loading with credentialsoutput.devtoolFallbackModuleFilenameTemplate
string
function (info)
A fallback used when the template string or function above yields duplicates.
See output.devtoolModuleFilenameTemplate
.
output.devtoolModuleFilenameTemplate
string = 'webpack://[namespace]/[resource-path]?[loaders]'
function (info) => string
This option is only used when devtool
uses an options which requires module names.
Customize the names used in each source map's sources
array. This can be done by passing a template string or function. For example, when using devtool: 'eval'
.
webpack.config.js
module.exports = {
//...
output: {
devtoolModuleFilenameTemplate: 'webpack://[namespace]/[resource-path]?[loaders]'
}
};
The following substitutions are available in template strings (via webpack's internal ModuleFilenameHelpers
):
Template | Description |
---|---|
[absolute-resource-path] | The absolute filename |
[all-loaders] | Automatic and explicit loaders and params up to the name of the first loader |
[hash] | The hash of the module identifier |
[id] | The module identifier |
[loaders] | Explicit loaders and params up to the name of the first loader |
[resource] | The path used to resolve the file and any query params used on the first loader |
[resource-path] | The path used to resolve the file without any query params |
[namespace] | The modules namespace. This is usually the library name when building as a library, empty otherwise |
When using a function, the same options are available camel-cased via the info
parameter:
module.exports = {
//...
output: {
devtoolModuleFilenameTemplate: info => {
return `webpack:///${info.resourcePath}?${info.loaders}`;
}
}
};
If multiple modules would result in the same name, output.devtoolFallbackModuleFilenameTemplate
is used instead for these modules.
output.devtoolNamespace
string
This option determines the modules namespace used with the output.devtoolModuleFilenameTemplate
. When not specified, it will default to the value of: output.library
. It's used to prevent source file path collisions in sourcemaps when loading multiple libraries built with webpack.
For example, if you have 2 libraries, with namespaces library1
and library2
, which both have a file ./src/index.js
(with potentially different contents), they will expose these files as webpack://library1/./src/index.js
and webpack://library2/./src/index.js
.
output.filename
string
function (pathData, assetInfo) => string
This option determines the name of each output bundle. The bundle is written to the directory specified by the output.path
option.
For a single entry
point, this can be a static name.
webpack.config.js
module.exports = {
//...
output: {
filename: 'bundle.js'
}
};
However, when creating multiple bundles via more than one entry point, code splitting, or various plugins, you should use one of the following substitutions to give each bundle a unique name...
Using entry name:
webpack.config.js
module.exports = {
//...
output: {
filename: '[name].bundle.js'
}
};
Using internal chunk id:
webpack.config.js
module.exports = {
//...
output: {
filename: '[id].bundle.js'
}
};
Using hashes generated from the generated content:
webpack.config.js
module.exports = {
//...
output: {
filename: '[contenthash].bundle.js'
}
};
Combining multiple substitutions:
webpack.config.js
module.exports = {
//...
output: {
filename: '[name].[contenthash].bundle.js'
}
};
Using function to return the filename:
webpack.config.js
module.exports = {
//...
output: {
filename: (pathData) => {
return pathData.chunk.name === 'main' ? '[name].js': '[name]/[name].js';
},
}
};
Make sure to read the Caching guide for details. There are more steps involved than just setting this option.
Note this option is called filename but you are still allowed to use something like 'js/[name]/bundle.js'
to create a folder structure.
Note this option does not affect output files for on-demand-loaded chunks. It only affects output files that are initially loaded. For on-demand-loaded chunk files the output.chunkFilename
option is used. Files created by loaders also aren't affected. In this case you would have to try the specific loader's available options.
The following substitutions are available in template strings (via webpack's internal TemplatedPathPlugin
):
Substitutions available on Compilation-level:
Template | Description |
---|---|
[fullhash] | The full hash of compilation |
[hash] | Same, but deprecated |
Substitutions available on Chunk-level:
Template | Description |
---|---|
[id] | The ID of the chunk |
[name] | The name of the chunk, if set, otherwise the ID of the chunk |
[chunkhash] | The hash of the chunk, including all elements of the chunk |
[contenthash] | The hash of the chunk, including only elements of this content type (affected by optimization.realContentHash ) |
Substitutions available on Module-level:
Template | Description |
---|---|
[id] | The ID of the module |
[moduleid] | Same, but deprecated |
[hash] | The hash of the module |
[modulehash] | Same, but deprecated |
[contenthash] | The hash of the content of the module |
Substitutions available on File-level:
Template | Description |
---|---|
[file] | Filename and path, without query or fragment |
[query] | Query with leading ? |
[fragment] | Fragment with leading # |
[base] | Only filename (including extensions), without path |
[filebase] | Same, but deprecated |
[path] | Only path, without filename |
[name] | Only filename without extension or path |
[ext] | Extension with leading . |
Substitutions available on URL-level:
Template | Description |
---|---|
[url] | URL |
The length of hashes ([hash]
, [contenthash]
or [chunkhash]
) can be specified using [hash:16]
(defaults to 20). Alternatively, specify output.hashDigestLength
to configure the length globally.
It is possible to filter out placeholder replacement when you want to use one of the placeholders in the actual file name. For example, to output a file [name].js
, you have to escape the [name]
placeholder by adding backslashes between the brackets. So that [\name\]
generates [name]
instead of getting replaced with the name
of the asset.
Example: [\id\]
generates [id]
instead of getting replaced with the id
.
If using a function for this option, the function will be passed an object containing data for the substitutions in the table above. Substitutions will be applied to the returned string too. The passed object will have this type: (properties available depending on context)
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
}
output.assetModuleFilename
string = '[hash][ext][query]'
The same as output.filename
but for Asset Modules
output.globalObject
string = 'window'
When targeting a library, especially when libraryTarget
is 'umd'
, this option indicates what global object will be used to mount the library. To make UMD build available on both browsers and Node.js, set output.globalObject
option to 'this'
. Defaults to self
for Web-like targets.
For example:
webpack.config.js
module.exports = {
// ...
output: {
library: 'myLib',
libraryTarget: 'umd',
filename: 'myLib.js',
globalObject: 'this'
}
};
output.uniqueName
string
A unique name of the webpack build to avoid multiple webpack runtimes to conflict when using globals. It defaults to output.library
name or the package name from package.json
in the context, if both aren't found, it is set to an ''
.
output.uniqueName
will be used to generate unique globals for:
webpack.config.js
module.exports = {
// ...
output: {
uniqueName: 'my-package-xyz'
}
};
output.hashDigest
string = 'hex'
The encoding to use when generating the hash. All encodings from Node.JS' hash.digest
are supported. Using 'base64'
for filenames might be problematic since it has the character /
in its alphabet. Likewise 'latin1'
could contain any character.
output.hashDigestLength
number = 20
The prefix length of the hash digest to use.
output.hashFunction
string = 'md4'
function
The hashing algorithm to use. All functions from Node.JS' crypto.createHash
are supported. Since 4.0.0-alpha2
, the hashFunction
can now be a constructor to a custom hash function. You can provide a non-crypto hash function for performance reasons.
module.exports = {
//...
output: {
hashFunction: require('metrohash').MetroHash64
}
};
Make sure that the hashing function will have update
and digest
methods available.
output.hashSalt
An optional salt to update the hash via Node.JS' hash.update
.
output.hotUpdateChunkFilename
string = '[id].[fullhash].hot-update.js'
Customize the filenames of hot update chunks. See output.filename
option for details on the possible values.
The only placeholders allowed here are [id]
and [fullhash]
, the default being:
webpack.config.js
module.exports = {
//...
output: {
hotUpdateChunkFilename: '[id].[fullhash].hot-update.js'
}
};
output.hotUpdateGlobal
string
Only used when target
is set to 'web'
, which uses JSONP for loading hot updates.
A JSONP function used to asynchronously load hot-update chunks.
For details see output.chunkLoadingGlobal
.
output.hotUpdateMainFilename
string = '[runtime].[fullhash].hot-update.json'
function
Customize the main hot update filename. [fullhash]
and [runtime]
are available as placeholder.
output.library
string
object
How the value of the output.library
is used depends on the value of the output.libraryTarget
option; please refer to that section for the complete details. Note that the default option for output.libraryTarget
is var
, so if the following configuration option is used:
webpack.config.js
module.exports = {
//...
output: {
library: 'MyLibrary'
}
};
The variable MyLibrary
will be bound with the return value of your entry file, if the resulting output is included as a script tag in an HTML page.
string: 'module' | 'text/javascript'
boolean = false
This option allows loading asynchronous chunks with a custom script type, such as <script type="module" ...>
.
module.exports = {
//...
output: {
scriptType: 'module'
}
};
output.libraryExport
string
[string]
Configure which module or modules will be exposed via the libraryTarget
. It is undefined
by default, same behaviour will be applied if you set libraryTarget
to an empty string e.g. ''
it will export the whole (namespace) object. The examples below demonstrate the effect of this configuration when using libraryTarget: 'var'
.
The following configurations are supported:
libraryExport: 'default'
- The default export of your entry point will be assigned to the library target:
// if your entry has a default export of `MyDefaultModule`
var MyDefaultModule = _entry_return_.default;
libraryExport: 'MyModule'
- The specified module will be assigned to the library target:
var MyModule = _entry_return_.MyModule;
libraryExport: ['MyModule', 'MySubModule']
- The array is interpreted as a path to a module to be assigned to the library target:
var MySubModule = _entry_return_.MyModule.MySubModule;
With the libraryExport
configurations specified above, the resulting libraries could be utilized as such:
MyDefaultModule.doSomething();
MyModule.doSomething();
MySubModule.doSomething();
string = 'var'
Configure how the library will be exposed. Any one of the following options can be used. Please note that this option works in conjunction with the value assigned to output.library
. For the following examples, it is assumed that the value of output.library
is configured as MyLibrary
.
These options assign the return value of the entry point (e.g. whatever the entry point exported) to the name provided by output.library
at whatever scope the bundle was included at.
libraryTarget: 'var'
β When your library is loaded, the return value of your entry point will be assigned to a variable:
var MyLibrary = _entry_return_;
// In a separate script...
MyLibrary.doSomething();
libraryTarget: 'assign'
β This will generate an implied global which has the potential to reassign an existing value (use with caution):
MyLibrary = _entry_return_;
Be aware that if MyLibrary
isn't defined earlier your library will be set in global scope.
libraryTarget: 'assign-properties'
// create the target object if it doesn't exist
MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;
// then copy the return value to MyLibrary
// just like 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');
These options assign the return value of the entry point (e.g. whatever the entry point exported) to a specific object under the name defined by output.library
.
If output.library
is not assigned a non-empty string, the default behavior is that all properties returned by the entry point will be assigned to the object as defined for the particular output.libraryTarget
, via the following code fragment:
(function(e, a) { for(var i in a) { e[i] = a[i]; } }(output.libraryTarget, _entry_return_));
libraryTarget: "this"
- The return value of your entry point will be assigned to this under the property named by output.library
. The meaning of this
is up to you:
this['MyLibrary'] = _entry_return_;
// In a separate script...
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if this is window
libraryTarget: 'window'
- The return value of your entry point will be assigned to the window
object using the output.library
value.
window['MyLibrary'] = _entry_return_;
window.MyLibrary.doSomething();
libraryTarget: 'global'
- The return value of your entry point will be assigned to the global
object using the output.library
value.
global['MyLibrary'] = _entry_return_;
global.MyLibrary.doSomething();
libraryTarget: 'commonjs'
- The return value of your entry point will be assigned to the exports
object using the output.library
value. As the name implies, this is used in CommonJS environments.
exports['MyLibrary'] = _entry_return_;
require('MyLibrary').doSomething();
These options will result in a bundle that comes with a complete header to ensure compatibility with various module systems. The output.library
option will take on a different meaning under the following output.libraryTarget
options.
libraryTarget: 'commonjs2'
- The return value of your entry point will be assigned to the module.exports
. As the name implies, this is used in CommonJS environments:
module.exports = _entry_return_;
require('MyLibrary').doSomething();
Note that output.library
can't be used with this particular output.libraryTarget
, for further details, please read this issue.
libraryTarget: 'amd'
- This will expose your library as an AMD module.
AMD modules require that the entry chunk (e.g. the first script loaded by the <script>
tag) be defined with specific properties, such as define
and require
which is typically provided by RequireJS or any compatible loaders (such as almond). Otherwise, loading the resulting AMD bundle directly will result in an error like define is not defined
.
So, with the following configuration...
module.exports = {
//...
output: {
library: 'MyLibrary',
libraryTarget: 'amd'
}
};
The generated output will be defined with the name "MyLibrary", i.e.
define('MyLibrary', [], function() {
return _entry_return_;
});
The bundle can be included as part of a script tag, and the bundle can be invoked like so:
require(['MyLibrary'], function(MyLibrary) {
// Do something with the library...
});
If output.library
is undefined, the following is generated instead.
define([], function() {
return _entry_return_;
});
This bundle will not work as expected, or not work at all (in the case of the almond loader) if loaded directly with a <script>
tag. It will only work through a RequireJS compatible asynchronous module loader through the actual path to that file, so in this case, the output.path
and output.filename
may become important for this particular setup if these are exposed directly on the server.
libraryTarget: 'amd-require'
- This packages your output with an immediately-executed AMD require(dependencies, factory)
wrapper.
The 'amd-require'
target allows for the use of AMD dependencies without needing a separate later invocation. As with the 'amd'
target, this depends on the appropriate require
function being available in the environment in which the webpack output is loaded.
With this target, the library name is ignored.
libraryTarget: 'umd'
- This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD and as global variable. Take a look at the UMD Repository to learn more.
In this case, you need the library
property to name your module:
module.exports = {
//...
output: {
library: 'MyLibrary',
libraryTarget: 'umd'
}
};
And finally the output is:
(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_;
});
Note that omitting library
will result in the assignment of all properties returned by the entry point be assigned directly to the root object, as documented under the object assignment section. Example:
module.exports = {
//...
output: {
libraryTarget: 'umd'
}
};
The output will be:
(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_;
});
Since webpack 3.1.0, you may specify an object for library
for differing names per targets:
module.exports = {
//...
output: {
library: {
root: 'MyLibrary',
amd: 'my-library',
commonjs: 'my-common-library'
},
libraryTarget: 'umd'
}
};
libraryTarget: 'system'
- This will expose your library as a System.register
module. This feature was first released in webpack 4.30.0.
System modules require that a global variable System
is present in the browser when the webpack bundle is executed. Compiling to System.register
format allows you to System.import('/bundle.js')
without additional configuration and have your webpack bundle loaded into the System module registry.
module.exports = {
//...
output: {
libraryTarget: 'system'
}
};
Output:
System.register([], function(_export) {
return {
setters: [],
execute: function() {
// ...
},
};
});
By adding output.library
to configuration in addition to having output.libraryTarget
set to system
, the output bundle will have the library name as an argument to System.register
:
System.register('my-library', [], function(_export) {
return {
setters: [],
execute: function() {
// ...
},
};
});
You can access SystemJS context via __system_context__
:
// 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);
});
libraryTarget: 'jsonp'
- This will wrap the return value of your entry point into a jsonp wrapper.
MyLibrary(_entry_return_);
The dependencies for your library will be defined by the externals
config.
output.importFunctionName
string = 'import'
The name of the native import()
function. Can be used for polyfilling, e.g. with dynamic-import-polyfill
.
webpack.config.js
module.exports = {
//...
output: {
importFunctionName: '__import__'
}
};
output.path
string = path.join(process.cwd(), 'dist')
The output directory as an absolute path.
webpack.config.js
const path = require('path');
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'dist/assets')
}
};
Note that [fullhash]
in this parameter will be replaced with a hash of the compilation. See the Caching guide for details.
output.pathinfo
boolean=true
string: 'verbose'
Tells webpack to include comments in bundles with information about the contained modules. This option defaults to true
in development
and false
in production
mode respectively. 'verbose'
shows more information like exports, runtime requirements and bailouts.
webpack.config.js
module.exports = {
//...
output: {
pathinfo: true
}
};
output.publicPath
string
function
This is an important option when using on-demand-loading or loading external resources like images, files, etc. If an incorrect value is specified you'll receive 404 errors while loading these resources.
This option specifies the public URL of the output directory when referenced in a browser. A relative URL is resolved relative to the HTML page (or <base>
tag). Server-relative URLs, protocol-relative URLs or absolute URLs are also possible and sometimes required, i. e. when hosting assets on a CDN.
The value of the option is prefixed to every URL created by the runtime or loaders. Because of this the value of this option ends with /
in most cases.
Simple rule: The URL of your output.path
from the view of the HTML page.
webpack.config.js
const path = require('path');
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'https://cdn.example.com/assets/'
}
};
For this configuration:
webpack.config.js
module.exports = {
//...
output: {
publicPath: '/assets/',
chunkFilename: '[id].chunk.js'
}
};
A request to a chunk will look like /assets/4.chunk.js
.
A loader outputting HTML might emit something like this:
<link href="/assets/spinner.gif" />
or when loading an image in CSS:
background-image: url(/assets/spinner.gif);
The webpack-dev-server also takes a hint from publicPath
, using it to determine where to serve the output files from.
Note that [fullhash]
in this parameter will be replaced with a hash of the compilation. See the Caching guide for details.
Examples:
module.exports = {
//...
output: {
// One of the below
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)
}
};
In cases where the publicPath
of output files can't be known at compile time, it can be left blank and set dynamically at runtime in the entry file using the free variable __webpack_public_path__
.
__webpack_public_path__ = myRuntimePublicPath;
// rest of your application entry
See this discussion for more information on __webpack_public_path__
.
output.sourceMapFilename
string = '[file].map[query]'
Configure how source maps are named. Only takes effect when devtool
is set to 'source-map'
, which writes an output file.
The [name]
, [id]
, [fullhash]
and [chunkhash]
substitutions from output.filename
can be used. In addition to those, you can use substitutions listed under Filename-level in Template strings.
output.sourcePrefix
string = ''
Change the prefix for each line in the output bundles.
webpack.config.js
module.exports = {
//...
output: {
sourcePrefix: '\t'
}
};
output.strictModuleExceptionHandling
boolean = false
Tell webpack to remove a module from the module instance cache (require.cache
) if it throws an exception when it is require
d.
It defaults to false
for performance reasons.
When set to false
, the module is not removed from cache, which results in the exception getting thrown only on the first require
call (making it incompatible with node.js).
For instance, consider module.js
:
throw new Error('error');
With strictModuleExceptionHandling
set to false
, only the first require
throws an exception:
// with strictModuleExceptionHandling = false
require('module'); // <- throws
require('module'); // <- doesn't throw
Instead, with strictModuleExceptionHandling
set to true
, all require
s of this module throw an exception:
// with strictModuleExceptionHandling = true
require('module'); // <- throws
require('module'); // <- also throws
output.umdNamedDefine
boolean
When using libraryTarget: "umd"
, setting output.umdNamedDefine
to true
will name the AMD module of the UMD build. Otherwise an anonymous define
is used.
module.exports = {
//...
output: {
umdNamedDefine: true
}
};
output.workerChunkLoading
string: 'require' | 'import-scripts' | 'async-node' | 'import' | 'universal'
boolean: false
The new option workerChunkLoading
controls the chunk loading of workers.
webpack.config.js
module.exports = {
//...
output: {
workerChunkLoading: false
}
};
output.enabledLibraryTypes
[string]
List of library types enabled for use by entry points.
module.exports = {
//...
output: {
enabledLibraryTypes: ['module']
}
};
output.futureEmitAssets
boolean = false
Tells webpack to use the future version of asset emitting logic, which allows freeing memory of assets after emitting. It could break plugins which assume that assets are still readable after they were emitted.
module.exports = {
//...
output: {
futureEmitAssets: true
}
};
output.environment
Tell webpack what kind of ES-features may be used in the generated runtime-code.
module.exports = {
output: {
environment: {
// The environment supports arrow functions ('() => { ... }').
arrowFunction: 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 an async import() function to import EcmaScript modules.
dynamicImport: false,
// The environment supports 'for of' iteration ('for (const x of array) { ... }').
forOf: true,
// The environment supports ECMAScript Module syntax to import ECMAScript modules (import ... from '...').
module: false,
}
}
};
output.compareBeforeEmit
boolean = true
Tells webpack to check if to be emitted file already exists and has the same content before writing to the output file system.
module.exports = {
//...
output: {
compareBeforeEmit: false
}
};
output.wasmLoading
boolean = false
string
Option to set the method of loading WebAssembly Modules. Methods included by default are 'fetch'
(web/WebWorker), 'async-node'
(Node.js), but others might be added by plugins.
The default value can be affected by different target
:
'fetch'
if target
is set to 'web'
, 'webworker'
, 'electron-renderer'
or 'node-webkit'
.'async-node'
if target
is set to 'node'
, 'async-node'
, 'electron-main'
or 'electron-preload'
.module.exports = {
//...
output: {
wasmLoading: 'fetch'
}
};
output.enabledWasmLoadingTypes
[string]
List of wasm loading types enabled for use by entry points.
module.exports = {
//...
output: {
enabledWasmLoadingTypes: ['fetch']
}
};
output.iife
boolean = true
Tells webpack to add IIFE wrapper around emitted code.
module.exports = {
//...
output: {
iife: true
}
};
output.module
boolean = true
Allow outputting JavaScript files as module type. It sets output.iife
to false
, output.libraryTarget
to 'module'
, output.scriptType
to 'module'
and terserOptions.module
to true
module.exports = {
//...
output: {
module: true
}
};
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: /\\.\\*/
These options change how modules are resolved. webpack provides reasonable defaults, but it is possible to change the resolving in detail. Have a look at Module Resolution for more explanation of how the resolver works.
resolve
object
Configure how modules are resolved. For example, when calling import 'lodash'
in ES2015, the resolve
options can change where webpack goes to look for 'lodash'
(see modules
).
webpack.config.js
module.exports = {
//...
resolve: {
// configuration options
}
};
resolve.alias
object
Create aliases to import
or require
certain modules more easily. For example, to alias a bunch of commonly used src/
folders:
webpack.config.js
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/')
}
}
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
A trailing $
can also be added to the given object's keys to signify an exact match:
webpack.config.js
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
xyz$: path.resolve(__dirname, 'path/to/file.js')
}
}
};
which would yield these results:
import Test1 from 'xyz'; // Exact match, so path/to/file.js is resolved and imported
import Test2 from 'xyz/file.js'; // Not an exact match, normal resolution takes place
The following table explains other cases:
alias: | import 'xyz' | import 'xyz/file.js' |
---|---|---|
{} | /abc/node_modules/xyz/index.js | /abc/node_modules/xyz/file.js |
{ xyz: '/abc/path/to/file.js' } | /abc/path/to/file.js | error |
{ xyz$: '/abc/path/to/file.js' } | /abc/path/to/file.js | /abc/node_modules/xyz/file.js |
{ xyz: './dir/file.js' } | /abc/dir/file.js | error |
{ xyz$: './dir/file.js' } | /abc/dir/file.js | /abc/node_modules/xyz/file.js |
{ xyz: '/some/dir' } | /some/dir/index.js | /some/dir/file.js |
{ xyz$: '/some/dir' } | /some/dir/index.js | /abc/node_modules/xyz/file.js |
{ xyz: './dir' } | /abc/dir/index.js | /abc/dir/file.js |
{ xyz: 'modu' } | /abc/node_modules/modu/index.js | /abc/node_modules/modu/file.js |
{ xyz$: 'modu' } | /abc/node_modules/modu/index.js | /abc/node_modules/xyz/file.js |
{ xyz: 'modu/some/file.js' } | /abc/node_modules/modu/some/file.js | error |
{ xyz: 'modu/dir' } | /abc/node_modules/modu/dir/index.js | /abc/node_modules/modu/dir/file.js |
{ xyz$: 'modu/dir' } | /abc/node_modules/modu/dir/index.js | /abc/node_modules/xyz/file.js |
index.js
may resolve to another file if defined in the package.json
.
/abc/node_modules
may resolve in /node_modules
too.
module.exports = {
//...
resolve: {
alias: {
_: [path.resolve(__dirname, 'src/utilities/'), path.resolve(__dirname, 'src/templates/')]
}
}
};
Setting resolve.alias
to false
will tell webpack to ignore a module.
module.exports = {
//...
resolve: {
alias: {
'ignored-module': false,
'./ignored-module': false,
}
}
};
resolve.aliasFields
[string]: ['browser']
Specify a field, such as browser
, to be parsed according to this specification.
webpack.config.js
module.exports = {
//...
resolve: {
aliasFields: ['browser']
}
};
resolve.cacheWithContext
boolean
(since webpack 3.1.0)
If unsafe cache is enabled, includes request.context
in the cache key. This option is taken into account by the enhanced-resolve
module. Since webpack 3.1.0 context in resolve caching is ignored when resolve or resolveLoader plugins are provided. This addresses a performance regression.
resolve.descriptionFiles
[string] = ['package.json']
The JSON files to use for descriptions.
webpack.config.js
module.exports = {
//...
resolve: {
descriptionFiles: ['package.json']
}
};
resolve.enforceExtension
boolean = false
If true
, it will not allow extension-less files. So by default require('./foo')
works if ./foo
has a .js
extension, but with this enabled only require('./foo.js')
will work.
webpack.config.js
module.exports = {
//...
resolve: {
enforceExtension: false
}
};
resolve.enforceModuleExtension
boolean = false
Tells webpack whether to require to use an extension for modules (e.g. loaders).
webpack.config.js
module.exports = {
//...
resolve: {
enforceModuleExtension: false
}
};
resolve.extensions
[string] = ['.wasm', '.mjs', '.js', '.json']
Attempt to resolve these extensions in order.
webpack.config.js
module.exports = {
//...
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json']
}
};
which is what enables users to leave off the extension when importing:
import File from '../path/to/file';
resolve.mainFields
[string]
When importing from an npm package, e.g. import * as D3 from 'd3'
, this option will determine which fields in its package.json
are checked. The default values will vary based upon the target
specified in your webpack configuration.
When the target
property is set to webworker
, web
, or left unspecified:
webpack.config.js
module.exports = {
//...
resolve: {
mainFields: ['browser', 'module', 'main']
}
};
For any other target (including node
):
webpack.config.js
module.exports = {
//...
resolve: {
mainFields: ['module', 'main']
}
};
For example, consider an arbitrary library called upstream
with a package.json
that contains the following fields:
{
"browser": "build/upstream.js",
"module": "index"
}
When we import * as Upstream from 'upstream'
this will actually resolve to the file in the browser
property. The browser
property takes precedence because it's the first item in mainFields
. Meanwhile, a Node.js application bundled by webpack will first try to resolve using the file in the module
field.
resolve.mainFiles
[string] = ['index']
The filename to be used while resolving directories.
webpack.config.js
module.exports = {
//...
resolve: {
mainFiles: ['index']
}
};
resolve.exportsFields
[string] = ['exports']
Fields in package.json that are used for resolving module requests. See package-exports guideline for more information.
webpack.config.js
module.exports = {
//...
resolve: {
exportsFields: ['exports', 'myCompanyExports']
}
};
resolve.modules
[string] = ['node_modules']
Tell webpack what directories should be searched when resolving modules.
Absolute and relative paths can both be used, but be aware that they will behave a bit differently.
A relative path will be scanned similarly to how Node scans for node_modules
, by looking through the current directory as well as its ancestors (i.e. ./node_modules
, ../node_modules
, and on).
With an absolute path, it will only search in the given directory.
webpack.config.js
module.exports = {
//...
resolve: {
modules: ['node_modules']
}
};
If you want to add a directory to search in that takes precedence over node_modules/
:
webpack.config.js
const path = require('path');
module.exports = {
//...
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules']
}
};
resolve.unsafeCache
RegExp
[RegExp]
boolean: true
Enable aggressive, but unsafe, caching of modules. Passing true
will cache everything.
webpack.config.js
module.exports = {
//...
resolve: {
unsafeCache: true
}
};
A regular expression, or an array of regular expressions, can be used to test file paths and only cache certain modules. For example, to only cache utilities:
webpack.config.js
module.exports = {
//...
resolve: {
unsafeCache: /src\/utilities/
}
};
resolve.plugins
A list of additional resolve plugins which should be applied. It allows plugins such as DirectoryNamedWebpackPlugin
.
webpack.config.js
module.exports = {
//...
resolve: {
plugins: [
new DirectoryNamedWebpackPlugin()
]
}
};
resolve.preferRelative
boolean
When enabled, webpack would prefer to resolve module requests as relative requests instead of using modules from node_modules
directories.
webpack.config.js
module.exports = {
//...
resolve: {
preferRelative: true
}
};
src/index.js
// let's say `src/logo.svg` exists
import logo1 from 'logo.svg'; // this is viable when `preferRelative` enabled
import logo2 from './logo.svg'; // otherwise you can only use relative path to resolve logo.svg
// `preferRelative` is enabled by default for `new URL()` case
const b = new URL('module/path', import.meta.url);
const a = new URL('./module/path', import.meta.url);
resolve.preferAbsolute
boolean
Prefer absolute paths to resolve.roots
when resolving.
wepack.config.js
module.exports = {
//...
resolve: {
preferAbsolute: true
}
};
resolve.symlinks
boolean = true
Whether to resolve symlinks to their symlinked location.
When enabled, symlinked resources are resolved to their real path, not their symlinked location. Note that this may cause module resolution to fail when using tools that symlink packages (like npm link
).
webpack.config.js
module.exports = {
//...
resolve: {
symlinks: true
}
};
resolve.cachePredicate
function(module) => boolean
A function which decides whether a request should be cached or not. An object is passed to the function with path
and request
properties. It must return a boolean.
webpack.config.js
module.exports = {
//...
resolve: {
cachePredicate: (module) => {
// additional logic
return true;
}
}
};
resolve.restrictions
[string, RegExp]
A list of resolve restrictions to restrict the paths that a request can be resolved on.
webpack.config.js
module.exports = {
//...
resolve: {
restrictions: [/\.(sass|scss|css)$/]
}
};
resolve.roots
[string]
A list of directories where requests of server-relative URLs (starting with '/') are resolved, defaults to context
configuration option. On non-Windows systems these requests are resolved as an absolute path first.
webpack.config.js
const fixtures = path.resolve(__dirname, 'fixtures');
module.exports = {
//...
resolve: {
roots: [__dirname, fixtures]
}
};
resolve.importsFields
[string]
Fields from package.json
which are used to provide the internal requests of a package (requests starting with #
are considered internal).
webpack.config.js
module.exports = {
//...
resolve: {
importsFields: ['browser', 'module', 'main']
}
};
resolve.fallback
boolean
Redirect module requests when normal resolving fails.
webpack.config.js
module.exports = {
//...
resolve: {
fallback: {
xyz: path.resolve(__dirname, 'path/to/file.js')
}
}
};
Configure resolve options by the type of module request.
[type: string]: ResolveOptions
module.exports = {
// ...
resolve: {
byDependency: {
// ...
esm: {
mainFields: ['browser', 'module']
},
commonjs: {
aliasFields: ['browser']
},
url: {
preferRelative: true
}
}
}
};
resolveLoader
object { modules [string] = ['node_modules'], extensions [string] = ['.js', '.json'], mainFields [string] = ['loader', 'main']}
This set of options is identical to the resolve
property set above, but is used only to resolve webpack's loader packages.
webpack.config.js
module.exports = {
//...
resolveLoader: {
modules: ['node_modules'],
extensions: ['.js', '.json'],
mainFields: ['loader', 'main']
}
};
resolveLoader.moduleExtensions
[string]
The extensions/suffixes that are used when resolving loaders. Since version two, we strongly recommend using the full name, e.g. example-loader
, as much as possible for clarity. However, if you really wanted to exclude the -loader
bit, i.e. just use example
, you can use this option to do so:
webpack.config.js
module.exports = {
//...
resolveLoader: {
moduleExtensions: ['-loader']
}
};
Since version 4 webpack runs optimizations for you depending on the chosen mode
, still all optimizations are available for manual configuration and overrides.
optimization.minimize
boolean = true
Tell webpack to minimize the bundle using the TerserPlugin or the plugin(s) specified in optimization.minimizer
.
webpack.config.js
module.exports = {
//...
optimization: {
minimize: false
}
};
optimization.minimizer
[TerserPlugin]
and or [function (compiler)]
Allows you to override the default minimizer by providing a different one or more customized TerserPlugin instances.
webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
cache: true,
parallel: true,
sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
// https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
}
}),
],
}
};
Or, as function:
module.exports = {
optimization: {
minimizer: [
(compiler) => {
const TerserPlugin = require('terser-webpack-plugin');
new TerserPlugin({ /* your config */ }).apply(compiler);
}
],
}
};
'...'
can be used in optimization.minimizer
to access the defaults.
module.exports = {
optimization: {
minimizer: [new CssMinimizer(), '...'],
}
};
optimization.splitChunks
object
By default webpack v4+ provides new common chunks strategies out of the box for dynamically imported modules. See available options for configuring this behavior in the SplitChunksPlugin page.
optimization.runtimeChunk
object
string
boolean
Setting optimization.runtimeChunk
to true
or 'multiple'
adds an additional chunk containing only the runtime to each entrypoint. This setting is an alias for:
webpack.config.js
module.exports = {
//...
optimization: {
runtimeChunk: {
name: entrypoint => `runtime~${entrypoint.name}`
}
}
};
The value 'single'
instead creates a runtime file to be shared for all generated chunks. This setting is an alias for:
webpack.config.js
module.exports = {
//...
optimization: {
runtimeChunk: {
name: 'runtime'
}
}
};
By setting optimization.runtimeChunk
to object
it is only possible to provide the name
property which stands for the name or name factory for the runtime chunks.
Default is false
: each entry chunk embeds runtime.
webpack.config.js
module.exports = {
//...
optimization: {
runtimeChunk: {
name: entrypoint => `runtimechunk~${entrypoint.name}`
}
}
};
optimization.emitOnErrors
boolean = false
Use the optimization.emitOnErrors
to emit assets whenever there are errors while compiling. This ensures that erroring assets are emitted. Critical errors are emitted into the generated code and will cause errors at runtime.
webpack.config.js
module.exports = {
//...
optimization: {
emitOnErrors: true
}
};
optimization.moduleIds
boolean = false
string: 'natural' | 'named' | 'deterministic' | 'size'
Tells webpack which algorithm to use when choosing module ids. Setting optimization.moduleIds
to false
tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. By default optimization.moduleIds
is set to false
.
The following string values are supported:
Option | Description |
---|---|
natural | Numeric ids in order of usage. |
named | Readable ids for better debugging. |
deterministic | Module names are hashed into small numeric values. |
size | Numeric ids focused on minimal initial download size. |
webpack.config.js
module.exports = {
//...
optimization: {
moduleIds: 'deterministic'
}
};
deterministic
option is useful for long term caching, but still results in smaller bundles compared to hashed
. Length of the numeric value is chosen to fill a maximum of 80% of the id space. By default a minimum length of 3 digits is used when optimization.moduleIds
is set to deterministic
. To override the default behaviour set optimization.moduleIds
to false
and use the webpack.ids.DeterministicModuleIdsPlugin
.
webpack.config.js
module.exports = {
//...
optimization: {
moduleIds: false
},
plugins: [
new webpack.ids.DeterministicModuleIdsPlugin({
maxLength: 5
})
]
};
optimization.chunkIds
boolean = false
string: 'natural' | 'named' | 'size' | 'total-size' | 'deterministic'
Tells webpack which algorithm to use when choosing chunk ids. Setting optimization.chunkIds
to false
tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. There are a couple of defaults for optimization.chunkIds
:
optimization.chunkIds
is set to 'named'
, while in production it is set to 'deterministic'
optimization.chunkIds
will be defaulted to 'natural'
The following string values are supported:
Option | Description |
---|---|
'natural' | Numeric ids in order of usage. |
'named' | Readable ids for better debugging. |
'deterministic' | Short numeric ids which will not be changing between compilation. Good for long term caching. Enabled by default for production mode. |
'size' | Numeric ids focused on minimal initial download size. |
'total-size' | numeric ids focused on minimal total download size. |
webpack.config.js
module.exports = {
//...
optimization: {
chunkIds: 'named'
}
};
By default, a minimum length of 3 digits is used when optimization.chunkIds
is set to 'deterministic'
. To override the default behaviour, set optimization.chunkIds
to false
and use the webpack.ids.DeterministicChunkIdsPlugin
.
webpack.config.js
module.exports = {
//...
optimization: {
chunkIds: false
},
plugins: [
new webpack.ids.DeterministicChunkIdsPlugin({
maxLength: 5
})
]
};
optimization.nodeEnv
boolean = false
string
Tells webpack to set process.env.NODE_ENV
to a given string value. optimization.nodeEnv
uses DefinePlugin unless set to false
. optimization.nodeEnv
defaults to mode if set, else falls back to 'production'
.
Possible values:
process.env.NODE_ENV
to.process.env.NODE_ENV
.webpack.config.js
module.exports = {
//...
optimization: {
nodeEnv: 'production'
}
};
optimization.mangleWasmImports
boolean = false
When set to true
tells webpack to reduce the size of WASM by changing imports to shorter strings. It mangles module and export names.
webpack.config.js
module.exports = {
//...
optimization: {
mangleWasmImports: true
}
};
optimization.removeAvailableModules
boolean = false
Tells webpack to detect and remove modules from chunks when these modules are already included in all parents. Setting optimization.removeAvailableModules
to true
will enable this optimization. Enabled by default in production
mode.
webpack.config.js
module.exports = {
//...
optimization: {
removeAvailableModules: true
}
};
optimization.removeEmptyChunks
boolean = true
Tells webpack to detect and remove chunks which are empty. Setting optimization.removeEmptyChunks
to false
will disable this optimization.
webpack.config.js
module.exports = {
//...
optimization: {
removeEmptyChunks: false
}
};
optimization.mergeDuplicateChunks
boolean = true
Tells webpack to merge chunks which contain the same modules. Setting optimization.mergeDuplicateChunks
to false
will disable this optimization.
webpack.config.js
module.exports = {
//...
optimization: {
mergeDuplicateChunks: false
}
};
optimization.flagIncludedChunks
boolean
Tells webpack to determine and flag chunks which are subsets of other chunks in a way that subsets donβt have to be loaded when the bigger chunk has been already loaded. By default optimization.flagIncludedChunks
is enabled in production
mode and disabled elsewise.
webpack.config.js
module.exports = {
//...
optimization: {
flagIncludedChunks: true
}
};
optimization.occurrenceOrder
boolean
Tells webpack to figure out an order of modules which will result in the smallest initial bundle. By default optimization.occurrenceOrder
is enabled in production
mode and disabled elsewise.
webpack.config.js
module.exports = {
//...
optimization: {
occurrenceOrder: false
}
};
optimization.providedExports
boolean
Tells webpack to figure out which exports are provided by modules to generate more efficient code for export * from ...
. By default optimization.providedExports
is enabled.
webpack.config.js
module.exports = {
//...
optimization: {
providedExports: false
}
};
optimization.usedExports
boolean = true
string: 'global'
Tells webpack to determine used exports for each module. This depends on optimization.providedExports
. Information collected by optimization.usedExports
is used by other optimizations or code generation i.e. exports are not generated for unused exports, export names are mangled to single char identifiers when all usages are compatible. Dead code elimination in minimizers will benefit from this and can remove unused exports.
webpack.config.js
module.exports = {
//...
optimization: {
usedExports: false
}
};
To opt-out from used exports analysis per runtime:
module.exports = {
//...
optimization: {
usedExports: 'global'
}
};
optimization.concatenateModules
boolean
Tells webpack to find segments of the module graph which can be safely concatenated into a single module. Depends on optimization.providedExports
and optimization.usedExports
. By default optimization.concatenateModules
is enabled in production
mode and disabled elsewise.
webpack.config.js
module.exports = {
//...
optimization: {
concatenateModules: true
}
};
optimization.sideEffects
boolean = true
string: 'flag'
Tells webpack to recognise the sideEffects
flag in package.json
or rules to skip over modules which are flagged to contain no side effects when exports are not used.
package.json
{
"name": "awesome npm module",
"version": "1.0.0",
"sideEffects": false
}
optimization.sideEffects
depends on optimization.providedExports
to be enabled. This dependency has a build time cost, but eliminating modules has positive impact on performance because of less code generation. Effect of this optimization depends on your codebase, try it for possible performance wins.
webpack.config.js
module.exports = {
//...
optimization: {
sideEffects: true
}
};
To only use the manual flag and do not analyse source code:
module.exports = {
//...
optimization: {
sideEffects: 'flag'
}
};
The 'flag'
value is used by default in non-production builds.
optimization.portableRecords
boolean
optimization.portableRecords
tells webpack to generate records with relative paths to be able to move the context folder.
By default optimization.portableRecords
is disabled. Automatically enabled if at least one of the records options provided to webpack config: recordsPath
, recordsInputPath
, recordsOutputPath
.
webpack.config.js
module.exports = {
//...
optimization: {
portableRecords: true
}
};
optimization.mangleExports
boolean
string: 'deterministic' | 'size'
optimization.mangleExports
allows to control export mangling.
By default optimization.mangleExports: 'deterministic'
is enabled in production
mode and disabled elsewise.
The following values are supported:
Option | Description |
---|---|
'size' | Short names - usually a single char - focused on minimal download size. |
'deterministic' | Short names - usually two chars - which will not change when adding or removing exports. Good for long term caching. |
true | Same as 'deterministic' |
false | Keep original name. Good for readablility and debugging. |
webpack.config.js
module.exports = {
//...
optimization: {
mangleExports: true
}
};
optimization.innerGraph
boolean = true
optimization.innerGraph
tells webpack whether to conduct inner graph analysis for unused exports.
webpack.config.js
module.exports = {
//...
optimization: {
innerGraph: false
}
};
optimization.realContentHash
boolean = true
Adds an additional hash compilation pass after the assets have been processed to get the correct asset content hashes. If realContentHash
is set to false
, internal data is used to calculate the hash and it can change when assets are identical.
webpack.config.js
module.exports = {
//...
optimization: {
realContentHash: false
}
};
The plugins
option is used to customize the webpack build process in a variety of ways. webpack comes with a variety built-in plugins available under webpack.[plugin-name]
. See Plugins page for a list of plugins and documentation but note that there are a lot more out in the community.
plugins
An array of webpack plugins. For example, DefinePlugin
allows you to create global constants which can be configured at compile time. This can be useful for allowing different behavior between development builds and release builds.
webpack.config.js
module.exports = {
//...
plugins: [
new webpack.DefinePlugin({
// Definitions...
})
]
};
A more complex example, using multiple plugins, might look something like this:
webpack.config.js
var webpack = require('webpack');
// importing plugins that do not come by default in webpack
var DashboardPlugin = require('webpack-dashboard/plugin');
// adding plugins to your configuration
module.exports = {
//...
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// compile time plugins
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
}),
// webpack-dev-server enhancement plugins
new DashboardPlugin(),
new webpack.HotModuleReplacementPlugin(),
]
};
webpack-dev-server can be used to quickly develop an application. See the development guide to get started.
This page describes the options that affect the behavior of webpack-dev-server (short: dev-server).
devServer
object
This set of options is picked up by webpack-dev-server and can be used to change its behavior in various ways. Here's a simple example that gzips and serves everything from our dist/
directory in the project root:
webpack.config.js
var path = require('path');
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
When the server is started, there will be a message prior to the list of resolved modules:
http://localhost:9000/
webpack output is served from /build/
Content not from webpack is served from /path/to/dist/
that will give some background on where the server is located and what it's serving.
If you're using dev-server through the Node.js API, the options in devServer
will be ignored. Pass the options as a second parameter instead: new WebpackDevServer(compiler, {...})
. See here for an example of how to use webpack-dev-server through the Node.js API.
devServer.after
function (app, server, compiler)
Provides the ability to execute custom middleware after all other middleware internally within the server.
webpack.config.js
module.exports = {
//...
devServer: {
after: function(app, server, compiler) {
// do fancy stuff
}
}
};
devServer.allowedHosts
[string]
This option allows you to whitelist services that are allowed to access the dev server.
webpack.config.js
module.exports = {
//...
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
Mimicking django's ALLOWED_HOSTS
, a value beginning with .
can be used as a subdomain wildcard. .host.com
will match host.com
, www.host.com
, and any other subdomain of host.com
.
webpack.config.js
module.exports = {
//...
devServer: {
// this achieves the same effect as the first example
// with the bonus of not having to update your config
// if new subdomains need to access the dev server
allowedHosts: [
'.host.com',
'host2.com'
]
}
};
To use this option with the CLI pass the --allowed-hosts
option a comma-delimited string.
webpack serve --entry ./entry/file --output-path ./output/path --allowed-hosts .host.com,host2.com
devServer.before
function (app, server, compiler)
Provides the ability to execute custom middleware prior to all other middleware internally within the server. This could be used to define custom handlers, for example:
webpack.config.js
module.exports = {
//...
devServer: {
before: function(app, server, compiler) {
app.get('/some/path', function(req, res) {
res.json({ custom: 'response' });
});
}
}
};
devServer.bonjour
boolean = false
This option broadcasts the server via ZeroConf networking on start
webpack.config.js
module.exports = {
//...
devServer: {
bonjour: true
}
};
Usage via the CLI
webpack serve --bonjour
devServer.clientLogLevel
string = 'info': 'silent' | 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'none' | 'warning'
When using inline mode, the console in your DevTools will show you messages e.g. before reloading, before an error or when Hot Module Replacement is enabled.
devServer.clientLogLevel
may be too verbose, you can turn logging off by setting it to 'silent'
.
webpack.config.js
module.exports = {
//...
devServer: {
clientLogLevel: 'silent'
}
};
Usage via the CLI
webpack serve --client-log-level silent
devServer.compress
boolean
Enable gzip compression for everything served:
webpack.config.js
module.exports = {
//...
devServer: {
compress: true
}
};
Usage via the CLI
webpack serve --compress
devServer.contentBase
boolean: false
string
[string]
number
Tell the server where to serve content from. This is only necessary if you want to serve static files. devServer.publicPath
will be used to determine where the bundles should be served from, and takes precedence.
By default, it will use your current working directory to serve content. To disable contentBase
set it to false
.
webpack.config.js
const path = require('path');
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
It is also possible to serve from multiple directories in case you want to serve static content at multiple URLs with contentBasePublicPath
:
webpack.config.js
const path = require('path');
module.exports = {
//...
devServer: {
contentBase: [path.join(__dirname, 'public'), path.join(__dirname, 'assets')]
}
};
Usage via the CLI
webpack serve --content-base ./path/to/content/dir
devServer.contentBasePublicPath
string = '/'
[string]
Tell the server at what URL to serve devServer.contentBase
static content. If there was a file assets/manifest.json
, it would be served at /serve-content-base-at-this-url/manifest.json
webpack.config.js
const path = require('path');
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'assets'),
contentBasePublicPath: '/serve-content-base-at-this-url'
}
};
Provide an array of strings in case you have multiple static folders set in contentBase
.
webpack.config.js
module.exports = {
//...
devServer: {
contentBase: [contentBasePublic, contentBaseOther],
contentBasePublicPath: [
contentBasePublicPath,
contentBasePublicOtherPath
]
}
};
devServer.disableHostCheck
boolean
When set to true
this option bypasses host checking. THIS IS NOT RECOMMENDED as apps that do not check the host are vulnerable to DNS rebinding attacks.
webpack.config.js
module.exports = {
//...
devServer: {
disableHostCheck: true
}
};
Usage via the CLI
webpack serve --disable-host-check
devServer.filename
πstring
This option lets you reduce the compilations in lazy mode. By default in lazy mode, every request results in a new compilation. With filename
, it's possible to only compile when a certain file is requested.
If output.filename
is set to 'bundle.js'
and devServer.filename
is used like this:
webpack.config.js
module.exports = {
//...
output: {
filename: 'bundle.js'
},
devServer: {
lazy: true,
filename: 'bundle.js'
}
};
It will now only compile the bundle when /bundle.js
is requested.
devServer.headers
πobject
Adds headers to all responses:
webpack.config.js
module.exports = {
//...
devServer: {
headers: {
'X-Custom-Foo': 'bar'
}
}
};
devServer.historyApiFallback
boolean = false
object
When using the HTML5 History API, the index.html
page will likely have to be served in place of any 404
responses. Enable devServer.historyApiFallback
by setting it to true
:
webpack.config.js
module.exports = {
//...
devServer: {
historyApiFallback: true
}
};
By passing an object this behavior can be controlled further using options like rewrites
:
webpack.config.js
module.exports = {
//...
devServer: {
historyApiFallback: {
rewrites: [
{ from: /^\/$/, to: '/views/landing.html' },
{ from: /^\/subpage/, to: '/views/subpage.html' },
{ from: /./, to: '/views/404.html' }
]
}
}
};
When using dots in your path (common with Angular), you may need to use the disableDotRule
:
webpack.config.js
module.exports = {
//...
devServer: {
historyApiFallback: {
disableDotRule: true
}
}
};
Usage via the CLI
webpack serve --history-api-fallback
For more options and information, see the connect-history-api-fallback documentation.
devServer.host
string = 'localhost'
Specify a host to use. If you want your server to be accessible externally, specify it like this:
webpack.config.js
module.exports = {
//...
devServer: {
host: '0.0.0.0'
}
};
Usage via the CLI
webpack serve --host 0.0.0.0
devServer.hot
boolean
Enable webpack's Hot Module Replacement feature:
webpack.config.js
module.exports = {
//...
devServer: {
hot: true
}
};
devServer.hotOnly
boolean
Enables Hot Module Replacement (see devServer.hot
) without page refresh as a fallback in case of build failures.
webpack.config.js
module.exports = {
//...
devServer: {
hotOnly: true
}
};
Usage via the CLI
webpack serve --hot only
devServer.http2
boolean = false
Serve over HTTP/2 using spdy. This option is ignored for Node 10.0.0 and above, as spdy is broken for those versions. The dev server will migrate over to Node's built-in HTTP/2 once Express supports it.
If devServer.http2
is not explicitly set to false
, it will default to true
when devServer.https
is enabled. When devServer.http2
is enabled but the server is unable to serve over HTTP/2, the server defaults to HTTPS.
HTTP/2 with a self-signed certificate:
webpack.config.js
module.exports = {
//...
devServer: {
http2: true
}
};
Provide your own certificate using the https option:
webpack.config.js
module.exports = {
//...
devServer: {
http2: true,
https: {
key: fs.readFileSync('/path/to/server.key'),
cert: fs.readFileSync('/path/to/server.crt'),
ca: fs.readFileSync('/path/to/ca.pem'),
}
}
};
Usage via CLI
webpack serve --http2
To pass your own certificate via CLI, use the following options
webpack serve --http2 --key ./path/to/server.key --cert ./path/to/server.crt --cacert ./path/to/ca.pem
devServer.https
boolean
object
By default, dev-server will be served over HTTP. It can optionally be served over HTTP/2 with HTTPS:
webpack.config.js
module.exports = {
//...
devServer: {
https: true
}
};
With the above setting, a self-signed certificate is used, but you can provide your own:
webpack.config.js
module.exports = {
//...
devServer: {
https: true,
key: fs.readFileSync('/path/to/server.key'),
cert: fs.readFileSync('/path/to/server.crt'),
ca: fs.readFileSync('/path/to/ca.pem'),
}
};
This object is passed straight to Node.js HTTPS module, so see the HTTPS documentation for more information.
Usage via the CLI
webpack serve --https
To pass your own certificate via the CLI use the following options
webpack serve --https --key ./path/to/server.key --cert ./path/to/server.crt --cacert ./path/to/ca.pem
devServer.index
string
The filename that is considered the index file.
webpack.config.js
module.exports = {
//...
devServer: {
index: 'index.html'
}
};
devServer.info
- CLI onlyboolean
Output cli information. It is enabled by default.
webpack serve --info false
devServer.injectClient
boolean = false
function (compilerConfig) => boolean
Tells devServer
to inject a client. Setting devServer.injectClient
to true
will result in always injecting a client. It is possible to provide a function to inject conditionally:
module.exports = {
//...
devServer: {
injectClient: (compilerConfig) => compilerConfig.name === 'only-include'
}
};
devServer.injectHot
boolean = false
function (compilerConfig) => boolean
Tells devServer
to inject a Hot Module Replacement. Setting devServer.injectHot
to true
will result in always injecting. It is possible to provide a function to inject conditionally:
module.exports = {
//...
devServer: {
hot: true,
injectHot: (compilerConfig) => compilerConfig.name === 'only-include'
}
};
devServer.inline
boolean
Toggle between the dev-server's two different modes. By default, the application will be served with inline mode enabled. This means that a script will be inserted in your bundle to take care of live reloading, and build messages will appear in the browser console.
It is also possible to use iframe mode, which uses an <iframe>
under a notification bar with messages about the build. To switch to iframe mode:
webpack.config.js
module.exports = {
//...
devServer: {
inline: false
}
};
Usage via the CLI
webpack serve --inline false
devServer.lazy
πboolean
When devServer.lazy
is enabled, the dev-server will only compile the bundle when it gets requested. This means that webpack will not watch any file changes. We call this lazy mode.
webpack.config.js
module.exports = {
//...
devServer: {
lazy: true
}
};
Usage via the CLI
webpack serve --lazy
devServer.liveReload
boolean = true
By default, the dev-server will reload/refresh the page when file changes are detected. devServer.hot
option must be disabled or devServer.watchContentBase
option must be enabled in order for liveReload
to take effect. Disable devServer.liveReload
by setting it to false
:
webpack.config.js
module.exports = {
//...
devServer: {
liveReload: false
}
};
Usage via the CLI
webpack serve --no-live-reload
devServer.mimeTypes
πobject
Allows dev-server to register custom mime types. The object is passed to the underlying webpack-dev-middleware
. See documentation for usage notes.
webpack.config.js
module.exports = {
//...
devServer: {
mimeTypes: { 'text/html': ['phtml'] }
}
};
devServer.noInfo
πboolean = false
Tells dev-server to suppress messages like the webpack bundle information. Errors and warnings will still be shown.
webpack.config.js
module.exports = {
//...
devServer: {
noInfo: true
}
};
devServer.onListening
function (server)
Provides an option to execute a custom function when webpack-dev-server
starts listening for connections on a port.
webpack.config.js
module.exports = {
//...
devServer: {
onListening: function(server) {
const port = server.listeningApp.address().port;
console.log('Listening on port:', port);
}
}
};
devServer.open
boolean = false
string
object
Tells dev-server to open the browser after server had been started. Set it to true
to open your default browser.
webpack.config.js
module.exports = {
//...
devServer: {
open: true
}
};
Provide browser name to use instead of the default one:
webpack.config.js
module.exports = {
//...
devServer: {
open: 'Google Chrome'
}
};
If you want to use flags when opening the browser like opening an incognito window (--incognito
flag), you can set open
to an object. The object accepts all open options, app
property must be an array. The first element in the array must be the browser name and the other following elements are the flags you want to use. For example:
webpack.config.js
module.exports = {
//...
devServer: {
open: {
app: ['Google Chrome', '--incognito', '--other-flag']
}
}
};
Usage via the CLI
webpack serve --open 'Google Chrome'
devServer.openPage
string
[string]
Specify a page to navigate to when opening the browser.
webpack.config.js
module.exports = {
//...
devServer: {
openPage: '/different/page'
}
};
Usage via the CLI
webpack serve --open-page /different/page
If you wish to specify multiple pages to open in the browser.
webpack.config.js
module.exports = {
//...
devServer: {
openPage: ['/different/page1', '/different/page2']
}
};
Usage via the CLI
webpack serve --open-page /different/page1,/different/page2
devServer.overlay
boolean = false
object: { errors boolean = false, warnings boolean = false }
Shows a full-screen overlay in the browser when there are compiler errors or warnings. If you want to show only compiler errors:
webpack.config.js
module.exports = {
//...
devServer: {
overlay: true
}
};
If you want to show warnings as well as errors:
webpack.config.js
module.exports = {
//...
devServer: {
overlay: {
warnings: true,
errors: true
}
}
};
devServer.pfx
string
When used via the CLI, a path to an SSL .pfx file. If used in options, it should be the bytestream of the .pfx file.
webpack.config.js
module.exports = {
//...
devServer: {
pfx: './path/to/file.pfx'
}
};
Usage via the CLI
webpack serve --pfx ./path/to/file.pfx
devServer.pfxPassphrase
string
The passphrase to a SSL PFX file.
webpack.config.js
module.exports = {
//...
devServer: {
pfxPassphrase: 'passphrase'
}
};
Usage via the CLI
webpack serve --pfx-passphrase passphrase
devServer.port
number
Specify a port number to listen for requests on:
webpack.config.js
module.exports = {
//...
devServer: {
port: 8080
}
};
Usage via the CLI
webpack serve --port 8080
devServer.proxy
object
[object, function]
Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.
The dev-server makes use of the powerful http-proxy-middleware package. Check out its documentation for more advanced usages. Note that some of http-proxy-middleware
's features do not require a target
key, e.g. its router
feature, but you will still need to include a target
key in your configuration here, otherwise webpack-dev-server
won't pass it along to http-proxy-middleware
).
With a backend on localhost:3000
, you can use this to enable proxying:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': 'http://localhost:3000'
}
}
};
A request to /api/users
will now proxy the request to http://localhost:3000/api/users
.
If you don't want /api
to be passed along, we need to rewrite the path:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {'^/api' : ''}
}
}
}
};
A backend server running on HTTPS with an invalid certificate will not be accepted by default. If you want to, modify your configuration like this:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'https://other-server.example.com',
secure: false
}
}
}
};
Sometimes you don't want to proxy everything. It is possible to bypass the proxy based on the return value of a function.
In the function you get access to the request, response, and proxy options.
null
or undefined
to continue processing the request with proxy.false
to produce a 404 error for the request.E.g. for a browser request, you want to serve an HTML page, but for an API request you want to proxy it. You could do something like this:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function(req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
}
}
}
}
};
If you want to proxy multiple, specific paths to the same target, you can use an array of one or more objects with a context
property:
webpack.config.js
module.exports = {
//...
devServer: {
proxy: [{
context: ['/auth', '/api'],
target: 'http://localhost:3000',
}]
}
};
Note that requests to root won't be proxied by default. To enable root proxying, the devServer.index
option should be specified as a falsy value:
webpack.config.js
module.exports = {
//...
devServer: {
index: '', // specify to enable root proxying
host: '...',
contentBase: '...',
proxy: {
context: () => true,
target: 'http://localhost:1234'
}
}
};
The origin of the host header is kept when proxying by default, you can set changeOrigin
to true
to override this behaviour. It is useful in some cases like using name-based virtual hosted sites.
webpack.config.js
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
}
};
devServer.progress
- CLI onlyboolean
Output running progress to console.
webpack serve --progress
devServer.public
string
When using inline mode and you're proxying dev-server, the inline client script does not always know where to connect to. It will try to guess the URL of the server based on window.location
, but if that fails you'll need to use this.
For example, the dev-server is proxied by nginx, and available on myapp.test
:
webpack.config.js
module.exports = {
//...
devServer: {
public: 'myapp.test:80'
}
};
Usage via the CLI
webpack serve --public myapp.test:80
devServer.publicPath
πstring = '/'
The bundled files will be available in the browser under this path.
Imagine that the server is running under http://localhost:8080
and output.filename
is set to bundle.js
. By default the devServer.publicPath
is '/'
, so your bundle is available as http://localhost:8080/bundle.js
.
Change devServer.publicPath
to put bundle under specific directory:
webpack.config.js
module.exports = {
//...
devServer: {
publicPath: '/assets/'
}
};
The bundle will now be available as http://localhost:8080/assets/bundle.js
.
It is also possible to use a full URL.
webpack.config.js
module.exports = {
//...
devServer: {
publicPath: 'http://localhost:8080/assets/'
}
};
The bundle will also be available as http://localhost:8080/assets/bundle.js
.
devServer.quiet
πboolean
With devServer.quiet
enabled, nothing except the initial startup information will be written to the console. This also means that errors or warnings from webpack are not visible.
webpack.config.js
module.exports = {
//...
devServer: {
quiet: true
}
};
Usage via the CLI
webpack serve --quiet
devServer.serveIndex
boolean = true
Tells dev-server to use serveIndex
middleware when enabled.
serveIndex
middleware generates directory listings on viewing directories that don't have an index.html file.
module.exports = {
//...
devServer: {
serveIndex: true
}
};
devServer.setup
function (app, server)
Here you can access the Express app object and add your own custom middleware to it. For example, to define custom handlers for some paths:
webpack.config.js
module.exports = {
//...
devServer: {
setup: function(app, server) {
app.get('/some/path', function(req, res) {
res.json({ custom: 'response' });
});
}
}
};
devServer.sockHost
string
Tells clients connected to devServer
to use provided socket host.
webpack.config.js
module.exports = {
//...
devServer: {
sockHost: 'myhost.test'
}
};
devServer.sockPath
string = '/sockjs-node'
The path at which to connect to the reloading socket.
webpack.config.js
module.exports = {
//...
devServer: {
sockPath: '/socket',
}
};
Usage via the CLI
webpack serve --sock-path /socket
devServer.sockPort
number
string
Tells clients connected to devServer
to use provided socket port.
webpack.config.js
module.exports = {
//...
devServer: {
sockPort: 8080
}
};
devServer.staticOptions
object
It is possible to configure advanced options for serving static files from contentBase
. See the Express documentation for the possible options.
webpack.config.js
module.exports = {
//...
devServer: {
staticOptions: {
redirect: false
}
}
};
devServer.stats
πstring: 'none' | 'errors-only' | 'minimal' | 'normal' | 'verbose'
object
This option lets you precisely control what bundle information gets displayed. This can be a nice middle ground if you want some bundle information, but not all of it.
To show only errors in your bundle:
webpack.config.js
module.exports = {
//...
devServer: {
stats: 'errors-only'
}
};
For more information, see the stats documentation.
devServer.stdin
- CLI onlyboolean
This option closes the server when stdin ends.
webpack serve --stdin
devServer.transportMode
string = 'sockjs': 'sockjs' | 'ws'
object
This option allows us either to choose the current devServer
transport mode for client/server individually or to provide custom client/server implementation. This allows to specify how browser or other client communicates with the devServer
.
The current default mode is 'sockjs'
. This mode uses SockJS-node as a server, and SockJS-client on the client.
'ws'
mode will become the default mode in the next major devServer
version. This mode uses ws as a server, and native WebSockets on the client.
Use 'ws'
mode:
module.exports = {
//...
devServer: {
transportMode: 'ws'
}
};
devServer.transportMode.client
string
path
To create a custom client implementation, create a class that extends BaseClient
.
Using path to CustomClient.js
, a custom WebSocket client implementation, along with the compatible 'ws'
server:
module.exports = {
//...
devServer: {
transportMode: {
client: require.resolve('./CustomClient'),
server: 'ws'
}
}
};
devServer.transportMode.server
string
path
function
To create a custom server implementation, create a class that extends BaseServer
.
Using path to CustomServer.js
, a custom WebSocket server implementation, along with the compatible 'ws'
client:
module.exports = {
//...
devServer: {
transportMode: {
client: 'ws',
server: require.resolve('./CustomServer')
}
}
};
Using class exported by CustomServer.js
, a custom WebSocket server implementation, along with the compatible 'ws'
client:
module.exports = {
//...
devServer: {
transportMode: {
client: 'ws',
server: require('./CustomServer')
}
}
};
Using custom, compatible WebSocket client and server implementations:
module.exports = {
//...
devServer: {
transportMode: {
client: require.resolve('./CustomClient'),
server: require.resolve('./CustomServer')
}
}
};
devServer.useLocalIp
boolean
This option lets the browser open with your local IP.
webpack.config.js
module.exports = {
//...
devServer: {
useLocalIp: true
}
};
Usage via the CLI
webpack serve --use-local-ip
devServer.watchContentBase
boolean
Tell dev-server to watch the files served by the devServer.contentBase
option. It is disabled by default. When enabled, file changes will trigger a full page reload.
webpack.config.js
module.exports = {
//...
devServer: {
watchContentBase: true
}
};
Usage via the CLI
webpack serve --watch-content-base
devServer.watchOptions
πobject
Control options related to watching the files.
webpack uses the file system to get notified of file changes. In some cases, this does not work. For example, when using Network File System (NFS). Vagrant also has a lot of problems with this. In these cases, use polling:
webpack.config.js
module.exports = {
//...
devServer: {
watchOptions: {
poll: true
}
}
};
If this is too heavy on the file system, you can change this to an integer to set the interval in milliseconds.
See WatchOptions for more options.
devServer.writeToDisk
πboolean = false
function (filePath) => boolean
Tells devServer
to write generated assets to the disk. The output is written to the output.path directory.
webpack.config.js
module.exports = {
//...
devServer: {
writeToDisk: true
}
};
Providing a Function
to devServer.writeToDisk
can be used for filtering. The function follows the same premise as Array#filter
in which a boolean return value tells if the file should be written to disk.
webpack.config.js
module.exports = {
//...
devServer: {
writeToDisk: (filePath) => {
return /superman\.css$/.test(filePath);
}
}
};
package.json
{
"scripts": "NODE_OPTIONS='--max-http-header-size=100000' webpack serve"
}
This option controls if and how source maps are generated.
Use the SourceMapDevToolPlugin
for a more fine grained configuration. See the source-map-loader
to deal with existing source maps.
devtool
string = 'eval'
false
Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically.
devtool | performance | production | quality | comment |
---|---|---|---|---|
(none) | build: fastest rebuild: fastest | yes | bundle | Recommended choice for production builds with maximum performance. |
eval | build: fast rebuild: fastest | no | generated | Recommended choice for development builds with maximum performance. |
eval-cheap-source-map | build: ok rebuild: fast | no | transformed | Tradeoff choice for development builds. |
eval-cheap-module-source-map | build: slow rebuild: fast | no | original lines | Tradeoff choice for development builds. |
eval-source-map | build: slowest rebuild: ok | no | original | Recommended choice for development builds with high quality SourceMaps. |
cheap-source-map | build: ok rebuild: slow | no | transformed | |
cheap-module-source-map | build: slow rebuild: slow | no | original lines | |
source-map | build: slowest rebuild: slowest | yes | original | Recommended choice for production builds with high quality SourceMaps. |
inline-cheap-source-map | build: ok rebuild: slow | no | transformed | |
inline-cheap-module-source-map | build: slow rebuild: slow | no | original lines | |
inline-source-map | build: slowest rebuild: slowest | no | original | Possible choice when publishing a single file |
eval-nosources-cheap-source-map | build: ok rebuild: fast | no | transformed | source code not included |
eval-nosources-cheap-module-source-map | build: slow rebuild: fast | no | original lines | source code not included |
eval-nosources-source-map | build: slowest rebuild: ok | no | original | source code not included |
inline-nosources-cheap-source-map | build: ok rebuild: slow | no | transformed | source code not included |
inline-nosources-cheap-module-source-map | build: slow rebuild: slow | no | original lines | source code not included |
inline-nosources-source-map | build: slowest rebuild: slowest | no | original | source code not included |
nosources-cheap-source-map | build: ok rebuild: slow | no | transformed | source code not included |
nosources-cheap-module-source-map | build: slow rebuild: slow | no | original lines | source code not included |
nosources-source-map | build: slowest rebuild: slowest | yes | original | source code not included |
hidden-nosources-cheap-source-map | build: ok rebuild: slow | no | transformed | no reference, source code not included |
hidden-nosources-cheap-module-source-map | build: slow rebuild: slow | no | original lines | no reference, source code not included |
hidden-nosources-source-map | build: slowest rebuild: slowest | yes | original | no reference, source code not included |
hidden-cheap-source-map | build: ok rebuild: slow | no | transformed | no reference |
hidden-cheap-module-source-map | build: slow rebuild: slow | no | original lines | no reference |
hidden-source-map | build: slowest rebuild: slowest | yes | original | no reference. Possible choice when using SourceMap only for error reporting purposes. |
shortcut | explanation |
---|---|
performance: build | How is the performance of the initial build affected by the devtool setting? |
performance: rebuild | How is the performance of the incremental build affected by the devtool setting? Slow devtools might reduce development feedback loop in watch mode. The scale is different compared to the build performance, as one would expect rebuilds to be faster than builds. |
production | Does it make sense to use this devtool for production builds? It's usually no when the devtool has a negative effect on user experience. |
quality: bundled | You will see all generated code of a chunk in a single blob of code. This is the raw output file without any devtooling support |
quality: generated | You will see the generated code, but each module is shown as separate code file in browser devtools. |
quality: transformed | You will see generated code after the preprocessing by loaders but before additional webpack transformations. Only source lines will be mapped and column information will be discarded resp. not generated. This prevents setting breakpoints in the middle of lines which doesn't work together with minimizer. |
quality: original lines | You will see the original code that you wrote, assuming all loaders support SourceMapping. Only source lines will be mapped and column information will be discarded resp. not generated. This prevents setting breakpoints in the middle of lines which doesn't work together with minimizer. |
quality: original | You will see the original code that you wrote, assuming all loaders support SourceMapping. |
eval-* addition | generate SourceMap per module and attach it via eval. Recommended for development, because of improved rebuild performance. Note that there is a windows defender issue, which causes huge slowdown due to virus scanning. |
inline-* addition | inline the SourceMap to the original file instead of creating a separate file. |
hidden-* addition | no reference to the SourceMap added. When SourceMap is not deployed, but should still be generated, e. g. for error reporting purposes. |
nosources-* addition | source code is not included in SourceMap. This can be useful when the original files should be referenced (further config options needed). |
Some of these values are suited for development and some for production. For development you typically want fast Source Maps at the cost of bundle size, but for production you want separate Source Maps that are accurate and support minimizing.
bundled code
- You see all generated code as a big blob of code. You don't see modules separated from each other.
generated code
- You see each module separated from each other, annotated with module names. You see the code generated by webpack. Example: Instead of import {test} from "module"; test();
you see something like var module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); module__WEBPACK_IMPORTED_MODULE_1__.a();
.
transformed code
- You see each module separated from each other, annotated with module names. You see the code before webpack transforms it, but after Loaders transpile it. Example: Instead of import {test} from "module"; class A extends test {}
you see something like import {test} from "module"; var A = function(_test) { ... }(test);
original source
- You see each module separated from each other, annotated with module names. You see the code before transpilation, as you authored it. This depends on Loader support.
without source content
- Contents for the sources are not included in the Source Maps. Browsers usually try to load the source from the webserver or filesystem. You have to make sure to set output.devtoolModuleFilenameTemplate
correctly to match source urls.
(lines only)
- Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author it this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.
The following options are ideal for development:
eval
- Each module is executed with eval()
and //@ sourceURL
. This is pretty fast. The main disadvantage is that it doesn't display line numbers correctly since it gets mapped to transpiled code instead of the original code (No Source Maps from Loaders).
eval-source-map
- Each module is executed with eval()
and a SourceMap is added as a DataUrl to the eval()
. Initially it is slow, but it provides fast rebuild speed and yields real files. Line numbers are correctly mapped since it gets mapped to the original code. It yields the best quality SourceMaps for development.
eval-cheap-source-map
- Similar to eval-source-map
, each module is executed with eval()
. It is "cheap" because it doesn't have column mappings, it only maps line numbers. It ignores SourceMaps from Loaders and only display transpiled code similar to the eval
devtool.
eval-cheap-module-source-map
- Similar to eval-cheap-source-map
, however, in this case Source Maps from Loaders are processed for better results. However Loader Source Maps are simplified to a single mapping per line.
The following options are not ideal for development nor production. They are needed for some special cases, i. e. for some 3rd party tools.
inline-source-map
- A SourceMap is added as a DataUrl to the bundle.
cheap-source-map
- A SourceMap without column-mappings ignoring loader Source Maps.
inline-cheap-source-map
- Similar to cheap-source-map
but SourceMap is added as a DataUrl to the bundle.
cheap-module-source-map
- A SourceMap without column-mappings that simplifies loader Source Maps to a single mapping per line.
inline-cheap-module-source-map
- Similar to cheap-module-source-map
but SourceMap is added as a DataUrl to the bundle.
These options are typically used in production:
(none)
(Omit the devtool
option) - No SourceMap is emitted. This is a good option to start with.
source-map
- A full SourceMap is emitted as a separate file. It adds a reference comment to the bundle so development tools know where to find it.
hidden-source-map
- Same as source-map
, but doesn't add a reference comment to the bundle. Useful if you only want SourceMaps to map error stack traces from error reports, but don't want to expose your SourceMap for the browser development tools.
nosources-source-map
- A SourceMap is created without the sourcesContent
in it. It can be used to map stack traces on the client without exposing all of the source code. You can deploy the Source Map file to the webserver.
webpack can compile for multiple environments or targets. To understand what a target
is in detail, read through the targets concept page.
target
string
[string]
false
Instructs webpack to target a specific environment. Defaults to 'browserslist'
or to 'web'
when no browserslist configuration was found.
string
The following string values are supported via WebpackOptionsApply
:
Option | Description |
---|---|
async-node[[X].Y] | Compile for usage in a Node.js-like environment (uses fs and vm to load chunks asynchronously) |
electron[[X].Y]-main | Compile for Electron for main process. |
electron[[X].Y]-renderer | Compile for Electron for renderer process, providing a target using JsonpTemplatePlugin , FunctionModulePlugin for browser environments and NodeTargetPlugin and ExternalsPlugin for CommonJS and Electron built-in modules. |
electron[[X].Y]-preload | Compile for Electron for renderer process, providing a target using NodeTemplatePlugin with asyncChunkLoading set to true , FunctionModulePlugin for browser environments and NodeTargetPlugin and ExternalsPlugin for CommonJS and Electron built-in modules. |
node[[X].Y] | Compile for usage in a Node.js-like environment (uses Node.js require to load chunks) |
node-webkit[[X].Y] | Compile for usage in WebKit and uses JSONP for chunk loading. Allows importing of built-in Node.js modules and nw.gui (experimental) |
nwjs[[X].Y] | The same as node-webkit |
web | Compile for usage in a browser-like environment (default) |
webworker | Compile as WebWorker |
esX | Compile for specified ECMAScript version. Examples: es5, es2020. |
browserslist | Infer a platform and the ES-features from a browserslist-config (default if browserslist config is available) |
For example, when the target
is set to "electron-main"
, webpack includes multiple electron specific variables.
A version of node
or electron
may be optionally specified. This is denoted by the [[X].Y]
in the table above.
webpack.config.js
module.exports = {
// ...
target: 'node12.18'
};
It helps determinate ES-features that may be used to generate a runtime-code (all the chunks and modules are wrapped by runtime code).
browserslist
If a project has a browserslist config, then webpack will use it for:
last 2 node versions
the same as target: "node"
with some output.environment
settings).Supported browserslist values:
browserslist
- use automatically resolved browserslist config and environment (from the nearest package.json
or BROWSERSLIST
environment variable, see browserslist documentation for details)browserslist:modern
- use modern
environment from automatically resolved browserslist configbrowserslist:last 2 versions
- use an explicit browserslist query (config will be ignored)browserslist:/path/to/config
- explicitly specify browserslist configbrowserslist:/path/to/config:modern
- explicitly specify browserslist config and an environment[string]
When multiple targets are passed, then common subset of features will be used:
webpack.config.js
module.exports = {
// ...
target: ['web', 'es5']
};
webpack will generate a runtime code for web platform and will use only ES5 features.
Not all targets may be mixed for now.
webpack.config.js
module.exports = {
// ...
target: ['web', 'node']
};
Will cause an error. webpack does not support universal target for now.
false
Set target
to false
if none of the predefined targets from the list above meet your needs, no plugins will be applied.
webpack.config.js
module.exports = {
// ...
target: false
};
Or you can apply specific plugins you want:
webpack.config.js
const webpack = require('webpack');
module.exports = {
// ...
target: false,
plugins: [
new webpack.JsonpTemplatePlugin(options.output),
new webpack.LoaderTargetPlugin('web')
]
};
When no information about the target or the environment features is provided, then ES2015 will be used.
webpack can watch files and recompile whenever they change. This page explains how to enable this and a couple of tweaks you can make if watching does not work properly for you.
watch
boolean = false
Turn on watch mode. This means that after the initial build, webpack will continue to watch for changes in any of the resolved files.
webpack.config.js
module.exports = {
//...
watch: true
};
object
A set of options used to customize watch mode:
webpack.config.js
module.exports = {
//...
watchOptions: {
aggregateTimeout: 200,
poll: 1000
}
};
number = 200
Add a delay before rebuilding once the first file changed. This allows webpack to aggregate any other changes made during this time period into one rebuild. Pass a value in milliseconds:
module.exports = {
//...
watchOptions: {
aggregateTimeout: 600
}
};
RegExp
string
[string]
For some systems, watching many files can result in a lot of CPU or memory usage. It is possible to exclude a huge folder like node_modules
using a regular expression:
webpack.config.js
module.exports = {
//...
watchOptions: {
ignored: /node_modules/
}
};
Alternatively, a glob pattern may be used:
webpack.config.js
module.exports = {
//...
watchOptions: {
ignored: '**/node_modules'
}
};
It is also possible to use multiple glob patterns:
webpack.config.js
module.exports = {
//...
watchOptions: {
ignored: ['**/files/**/*.js', '**/node_modules']
}
};
In addition, you can specify an absolute path:
const path = require('path');
module.exports = {
//...
watchOptions: {
ignored: [
path.posix.resolve(__dirname, './ignored-dir')
]
}
};
When using glob patterns, we convert them to regular expressions with glob-to-regexp
, so make sure to get yourself familiar with it before you use glob patterns for watchOptions.ignored
.
boolean = false
number
Turn on polling by passing true
, or specifying a poll interval in milliseconds:
webpack.config.js
module.exports = {
//...
watchOptions: {
poll: 1000 // Check for changes every second
}
};
Follow symbolic links while looking for a file. This is usually not needed as webpack already resolves symlinks with resolve.symlinks
.
boolean
module.exports = {
//...
watchOptions: {
followSymlinks: true
}
};
If you are experiencing any issues, please see the following notes. There are a variety of reasons why webpack might miss a file change.
Verify that webpack is not being notified of changes by running webpack with the --progress flag. If progress shows on save but no files are outputted, it is likely a configuration issue, not a file watching issue.
webpack --watch --progress
Verify that you have enough available watchers in your system. If this value is too low, the file watcher in Webpack won't recognize the changes:
cat /proc/sys/fs/inotify/max_user_watches
Arch users, add fs.inotify.max_user_watches=524288
to /etc/sysctl.d/99-sysctl.conf
and then execute sysctl --system
. Ubuntu users (and possibly others), execute: echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
.
On macOS, folders can get corrupted in certain scenarios. See this article.
Because webpack expects absolute paths for many configuration options such as __dirname + '/app/folder'
the Windows \
path separator can break some functionality.
Use the correct separators. I.e. path.resolve(__dirname, 'app/folder')
or path.join(__dirname, 'app', 'folder')
.
On some machines Vim is preconfigured with the backupcopy option set to auto
. This could potentially cause problems with the system's file watching mechanism. Switching this option to yes
will make sure a copy of the file is made and the original one overwritten on save.
:set backupcopy=yes
When using the JetBrains WebStorm IDE, you may find that saving changed files does not trigger the watcher as you might expect. Try disabling the safe write
option in the settings, which determines whether files are saved to a temporary location first before the originals are overwritten: uncheck File > {Settings|Preferences} > Appearance & Behavior > System Settings > Use "safe write" (save changes to a temporary file first)
.
The externals
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 to library developers, however there are a variety of applications for it.
externals
string
[string]
object
function
RegExp
Prevent bundling of certain import
ed packages and instead retrieve these external dependencies at runtime.
For example, to include jQuery from a CDN instead of bundling it:
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'
}
};
This leaves any dependent modules unchanged, i.e. the code shown below will still work:
import $ from 'jquery';
$('.my-element').animate(/* ... */);
The bundle with external dependencies can be used in various module contexts, such as CommonJS, AMD, global and ES2015 modules. The external library may be available in any of these forms:
module.exports.default
.commonjs
but using AMD module system.The following syntaxes are accepted...
See the example above. The property name jquery
indicates that the module jquery
in import $ from 'jquery'
should be excluded. In order to replace this module, the value jQuery
will be used to retrieve a global jQuery
variable. In other words, when a string is provided it will be treated as root
(defined above and below).
On the other hand, if you want to externalise a library that is available as a CommonJS module, you can provide the external library type together with the library name.
For example, if you want to exclude fs-extra
from the output bundle and import it during the runtime instead, you can specify it as follows:
module.exports = {
// ...
externals: {
'fs-extra': 'commonjs2 fs-extra',
}
};
This leaves any dependent modules unchanged, i.e. the code shown below:
import fs from 'fs-extra';
will compile to something like:
const fs = require('fs-extra');
[string]
module.exports = {
//...
externals: {
subtract: ['./math', 'subtract']
}
};
subtract: ['./math', 'subtract']
allows you select part of a commonjs module, where ./math
is the module and your bundle only requires the subset under the subtract
variable. This example would translate to require('./math').subtract;
module.exports = {
//...
externals : {
react: 'react'
},
// or
externals : {
lodash : {
commonjs: 'lodash',
amd: 'lodash',
root: '_' // indicates global variable
}
},
// 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 as lodash
under AMD and CommonJS module systems but available as _
in a global variable form. subtract
here is available via the property subtract
under the global math
object (e.g. window['math']['subtract']
).
function ({ context, request, contextInfo, getResolve }, callback)
function ({ context, request, contextInfo, getResolve }) => promise
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 the node_modules
directory and provides options to whitelist 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
(string
): Contains information about the issuer (e.g. the layer).ctx.getResolve
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. Can accept a string in the format ${type} ${path}
, or one of the other standard external formats (string
, [string]
, or object
)type
(string
): Optional parameter that indicates the module type (if it has not already been indicated in the result
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 path
return callback(null, 'commonjs ' + request);
}
// Continue without externalizing the import
callback();
}
]
};
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 module
callback(null, {
root: 'componentsGlobal',
commonjs: '@scope/components',
commonjs2: '@scope/components',
amd: 'components'
});
}
]
};
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 named jQuery
, capitalized or not, or $
would be externalized.
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']
},
// Function
function({ context, request }, callback) {
if (/^yourregex$/.test(request)){
return callback(null, 'commonjs ' + request);
}
callback();
},
// Regex
/^(jquery|\$)$/i
]
};
For more information on how to use this configuration, please refer to the article on how to author a library.
byLayer
function
object
Specify externals by layer.
webpack.config.js
module.exports = {
externals : {
byLayer : {
layer: {
external1: 'var 43'
}
}
}
};
externalsType
string = 'var'
Specifies the default type of externals. amd
, umd
, system
and jsonp
externals depend on the output.libraryTarget
being set to the same value e.g. you can only consume amd
externals within an amd
library.
Supported types:
'var'
'module'
'assign'
'this'
'window'
'self'
'global'
'commonjs'
'commonjs-module'
'amd'
'amd-require'
'umd'
'umd2'
'jsonp'
'system'
'promise'
- same as 'var'
but awaits the result (async module)'import'
- uses import()
to load a native EcmaScript module (async module)'script'
- load script exposing predefined global variables with HTML <script>
elementwebpack.config.js
module.exports = {
//...
externalsType: 'promise'
};
script
External script can be loaded from any URL when externalsType
is set to 'script'
. The <script>
tag would be removed after the script has been loaded.
module.exports = {
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 = {
externals: {
packageName: 'global@http://example.com/script.js' // no properties here
}
};
Let's load a lodash
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 variable head
and global window._
will be exposed when you import
lodash
:
import head from 'lodash';
console.log(head([1, 2, 3])); // logs 1 here
console.log(window._.head(['a', 'b'])); // logs a here
externalsPresets
object
Enable presets of externals for specific targets.
Option | Description | Input Type |
---|---|---|
electron | Treat common electron built-in modules in main and preload context like electron , ipc or shell as external and load them via require() when used. | boolean |
electronMain | Treat electron built-in modules in the main context like app , ipc-main or shell as external and load them via require() when used. | boolean |
electronPreload | Treat electron built-in modules in the preload context like web-frame , ipc-renderer or shell as external and load them via require() when used. | boolean |
electronRenderer | Treat electron built-in modules in the renderer context like web-frame , ipc-renderer or shell as external and load them via require() when used. | boolean |
node | Treat node.js built-in modules like fs , path or vm as external and load them via require() when used. | boolean |
nwjs | Treat NW.js legacy nw.gui module as external and load it via require() when used. | boolean |
web | Treat references to http(s)://... and std:... as external and load them via import when used. (Note that this changes execution order as externals are executed before any other code in the chunk). | boolean |
webAsync | Treat references to http(s)://... and std:... as external and load them via async import() when used (Note that this external type is an async module, which has various effects on the execution). | boolean |
Example
Using node
preset will not bundle built-in modules and treats them as external and loads them via require()
when used.
webpack.config.js
module.exports = {
// ...
externalsPresets:{
node: true
}
};
These options allows you to control how webpack notifies you of assets and entry points that exceed a specific file limit. This feature was inspired by the idea of webpack Performance Budgets.
performance
object
Configure how performance hints are shown. For example if you have an asset that is over 250kb, webpack will emit a warning notifying you of this.
performance.hints
string = 'warning': 'error' | 'warning'
boolean: false
Turns hints on/off. In addition, tells webpack to throw either an error or a warning when hints are found.
Given an asset is created that is over 250kb:
module.exports = {
//...
performance: {
hints: false
}
};
No hint warnings or errors are shown.
module.exports = {
//...
performance: {
hints: 'warning'
}
};
A warning will be displayed notifying you of a large asset. We recommend something like this for development environments.
module.exports = {
//...
performance: {
hints: 'error'
}
};
An error will be displayed notifying you of a large asset. We recommend using hints: "error"
during production builds to help prevent deploying production bundles that are too large, impacting webpage performance.
performance.maxEntrypointSize
number = 250000
An entry point represents all assets that would be utilized during initial load time for a specific entry. This option controls when webpack should emit performance hints based on the maximum entry point size in bytes.
module.exports = {
//...
performance: {
maxEntrypointSize: 400000
}
};
performance.maxAssetSize
number = 250000
An asset is any emitted file from webpack. This option controls when webpack emits a performance hint based on individual asset size in bytes.
module.exports = {
//...
performance: {
maxAssetSize: 100000
}
};
performance.assetFilter
function(assetFilename) => boolean
This property allows webpack to control what files are used to calculate performance hints. The default function is:
function assetFilter(assetFilename) {
return !(/\.map$/.test(assetFilename));
}
You can override this property by passing your own function in:
module.exports = {
//...
performance: {
assetFilter: function(assetFilename) {
return assetFilename.endsWith('.js');
}
}
};
The example above will only give you performance hints based on .js
files.
The following Node.js options configure whether to polyfill or mock certain Node.js globals.
This feature is provided by webpack's internal NodeStuffPlugin
plugin.
node
boolean: false
object
webpack.config.js
module.exports = {
//...
node: {
global: false,
__filename: false,
__dirname: false,
}
};
Since webpack 3.0.0, the node
option may be set to false
to completely turn off the NodeStuffPlugin
plugin.
node.global
boolean
See the Node.js documentation for the exact behavior of this object.
Options:
true
: Provide a polyfill.false
: Provide nothing. Code that expects this object may crash with a ReferenceError
.node.__filename
boolean
string: 'mock' | 'eval-only'
Options:
true
: The filename of the input file relative to the context
option.false
: Webpack won't touch your __filename
code, which means you have the regular Node.js __filename
behavior. The filename of the output file when run in a Node.js environment.'mock'
: The fixed value '/index.js'
.'eval-only'
node.__dirname
boolean
string: 'mock' | 'eval-only'
Options:
true
: The dirname of the input file relative to the context
option.false
: Webpack won't touch your __dirname
code, which means you have the regular Node.js __dirname
behavior. The dirname of the output file when run in a Node.js environment.'mock'
: The fixed value '/'
.'eval-only'
object
string
The stats
option lets you precisely control what bundle information gets displayed. This can be a nice middle ground if you don't want to use quiet
or noInfo
because you want some bundle information, but not all of it.
webpack.js.org
module.exports = {
//...
stats: 'errors-only'
};
webpack comes with certain presets available for the stats output:
Preset | Alternative | Description |
---|---|---|
'errors-only' | none | Only output when errors happen |
'errors-warnings' | none | Only output errors and warnings happen |
'minimal' | none | Only output when errors or new compilation happen |
'none' | false | Output nothing |
'normal' | true | Standard output |
'verbose' | none | Output everything |
'detailed' | none | Output everything except chunkModules and chunkRootModules |
It is possible to specify which information you want to see in the stats output.
stats.all
A fallback value for stats options when an option is not defined. It has precedence over local webpack defaults.
module.exports = {
//...
stats: {
all: undefined
}
};
stats.assets
boolean = true
Tells stats
whether to show the asset information. Set stats.assets
to false
to hide it.
module.exports = {
//...
stats: {
assets: false
}
};
stats.assetsSort
string = 'id'
Tells stats
to sort the assets by a given field. All of the sorting fields are allowed to be used as values for stats.assetsSort
. Use !
prefix in the value to reverse the sort order by a given field.
module.exports = {
//...
stats: {
assetsSort: '!size'
}
};
stats.builtAt
boolean = true
Tells stats
whether to add the build date and the build time information. Set stats.builtAt
to false
to hide it.
module.exports = {
//...
stats: {
builtAt: false
}
};
stats.moduleAssets
boolean = true
Tells stats
whether to add information about assets inside modules. Set stats.moduleAssets
to false
to hide it.
module.exports = {
//...
stats: {
moduleAssets: false
}
};
stats.cached
boolean = true
Tells stats
whether to add information about the cached modules (not the ones that were built).
module.exports = {
//...
stats: {
cached: false
}
};
stats.assetsSpace
number = 15
Tells stats
how many items of assets should be displayed (groups will be collapsed to fit this space).
module.exports = {
//...
stats: {
assetsSpace: 15
}
};
stats.modulesSpace
number = 15
Tells stats
how many items of modules should be displayed (groups will be collapsed to fit this space).
module.exports = {
//...
stats: {
modulesSpace: 15
}
};
stats.chunkModulesSpace
number = 10
Tells stats
how many items of chunk modules should be displayed (groups will be collapsed to fit this space).
module.exports = {
//...
stats: {
chunkModulesSpace: 15
}
};
stats.nestedModulesSpace
number = 10
Tells stats
how many items of nested modules should be displayed (groups will be collapsed to fit this space).
module.exports = {
//...
stats: {
nestedModulesSpace: 15
}
};
stats.cachedModules
boolean = true
Tells stats
whether to add information about cached (not built) modules.
module.exports = {
//...
stats: {
cachedModules: false
}
};
stats.runtimeModules
boolean = true
Tells stats
whether to add information about runtime modules.
module.exports = {
//...
stats: {
runtimeModules: false
}
};
stats.dependentModules
boolean
Tells stats
whether to show chunk modules that are dependencies of other modules of the chunk.
module.exports = {
//...
stats: {
dependentModules: false
}
};
stats.groupAssetsByChunk
boolean
Tells stats
whether to group assets by how their are related to chunks.
module.exports = {
//...
stats: {
groupAssetsByChunk: false
}
};
stats.groupAssetsByEmitStatus
boolean
Tells stats
whether to group assets by their status (emitted, compared for emit or cached).
module.exports = {
//...
stats: {
groupAssetsByEmitStatus: false
}
};
stats.groupAssetsByInfo
boolean
Tells stats
whether to group assets by their asset info (immutable, development, hotModuleReplacement, etc).
module.exports = {
//...
stats: {
groupAssetsByInfo: false
}
};
stats.groupModulesByAttributes
boolean
Tells stats
whether to group modules by their attributes (errors, warnings, assets, optional, orphan, or dependent).
module.exports = {
//...
stats: {
groupModulesByAttributes: false
}
};
stats.cachedAssets
boolean = true
Tells stats
whether to add information about the cached assets. Setting stats.cachedAssets
to false
will tell stats
to only show the emitted files (not the ones that were built).
module.exports = {
//...
stats: {
cachedAssets: false
}
};
stats.children
boolean = true
Tells stats
whether to add information about the children.
module.exports = {
//...
stats: {
children: false
}
};
stats.chunks
boolean = true
Tells stats
whether to add information about the chunk. Setting stats.chunks
to false
results in a less verbose output.
module.exports = {
//...
stats: {
chunks: false
}
};
stats.chunkGroups
boolean = true
Tells stats
whether to add information about the namedChunkGroups
.
module.exports = {
//...
stats: {
chunkGroups: false
}
};
stats.chunkModules
boolean = true
Tells stats
whether to add information about the built modules to information about the chunk.
module.exports = {
//...
stats: {
chunkModules: false
}
};
stats.chunkOrigins
boolean = true
Tells stats
whether to add information about the origins of chunks and chunk merging.
module.exports = {
//...
stats: {
chunkOrigins: false
}
};
stats.chunksSort
string = 'id'
Tells stats
to sort the chunks by a given field. All of the sorting fields are allowed to be used as values for stats.chunksSort
. Use !
prefix in the value to reverse the sort order by a given field.
module.exports = {
//...
stats: {
chunksSort: 'name'
}
};
stats.context
string = '../src/'
Sets the context directory for shortening the request information.
module.exports = {
//...
stats: {
context: '../src/components/'
}
};
stats.colors
boolean = false
object
Tells stats
whether to output in the different colors.
module.exports = {
//...
stats: {
colors: true
}
};
It is also available as a CLI flag:
webpack-cli --colors
You can specify your own terminal output colors using ANSI escape sequences
module.exports = {
//...
colors: {
green: '\u001b[32m',
},
};
stats.depth
boolean = false
Tells stats
whether to display the distance from the entry point for each module.
module.exports = {
//...
stats: {
depth: true
}
};
stats.entrypoints
boolean = true
string = 'auto'
Tells stats
whether to display the entry points with the corresponding bundles.
module.exports = {
//...
stats: {
entrypoints: false
}
};
When stats.entrypoints
is set to 'auto'
, webpack will decide automatically whether to display the entry points in the stats output.
stats.env
boolean = false
Tells stats
whether to display the --env
information.
module.exports = {
//...
stats: {
env: true
}
};
stats.orphanModules
boolean = false
Tells stats
whether to hide orphan
modules. A module is an orphan
if it is not included in any chunk. Orphan modules are hidden by default in stats
.
module.exports = {
//...
stats: {
orphanModules: true
}
};
stats.errors
boolean = true
Tells stats
whether to display the errors.
module.exports = {
//...
stats: {
errors: false
}
};
stats.errorDetails
boolean = true
Tells stats
whether to add the details to the errors.
module.exports = {
//...
stats: {
errorDetails: false
}
};
stats.errorStack
boolean = true
Tells stats
whether to show stack trace of errors.
module.exports = {
//...
stats: {
errorStack: false
}
};
stats.excludeAssets
array = []: string | RegExp | function (assetName) => boolean
string
RegExp
function (assetName) => boolean
Tells stats
to exclude the matching assets information. This can be done with a string
, a RegExp
, a function
that is getting the assets name as an argument and returns a boolean
. stats.excludeAssets
can be an array
of any of the above.
module.exports = {
//...
stats: {
excludeAssets: [
'filter',
/filter/,
(assetName) => assetName.contains('moduleA')
]
}
};
stats.excludeModules
array = []: string | RegExp | function (assetName) => boolean
string
RegExp
function (assetName) => boolean
boolean: false
Tells stats
to exclude the matching modules information. This can be done with a string
, a RegExp
, a function
that is getting the module's source as an argument and returns a boolean
. stats.excludeModules
can be an array
of any of the above. stats.excludeModules
's configuration is merged with the stats.exclude
's configuration value.
module.exports = {
//...
stats: {
excludeModules: [
'filter',
/filter/,
(moduleSource) => true
]
}
};
Setting stats.excludeModules
to false
will disable the exclude behaviour.
module.exports = {
//...
stats: {
excludeModules: false
}
};
stats.exclude
See stats.excludeModules
.
stats.hash
boolean = true
Tells stats
whether to add information about the hash of the compilation.
module.exports = {
//...
stats: {
hash: false
}
};
stats.logging
string = 'info': 'none' | 'error' | 'warn' | 'info' | 'log' | 'verbose'
boolean
Tells stats
whether to add logging output.
'none'
, false
- disable logging'error'
- errors only'warn'
- errors and warnings only'info'
- errors, warnings, and info messages'log'
, true
- errors, warnings, info messages, log messages, groups, clears. Collapsed groups are displayed in a collapsed state.'verbose'
- log everything except debug and trace. Collapsed groups are displayed in expanded state.module.exports = {
//...
stats: {
logging: 'verbose'
}
};
stats.loggingDebug
array = []: string | RegExp | function (name) => boolean
string
RegExp
function (name) => boolean
Tells stats
to include the debug information of the specified loggers such as Plugins or Loaders. When stats.logging
is set to false
, stats.loggingDebug
option is ignored.
module.exports = {
//...
stats: {
loggingDebug: [
'MyPlugin',
/MyPlugin/,
/webpack/, // To get core logging
(name) => name.contains('MyPlugin')
]
}
};
stats.loggingTrace
boolean = true
Enable stack traces in the logging output for errors, warnings and traces. Set stats.loggingTrace
to hide the trace.
module.exports = {
//...
stats: {
loggingTrace: false
}
};
stats.modules
boolean = true
Tells stats
whether to add information about the built modules.
module.exports = {
//...
stats: {
modules: false
}
};
stats.modulesSort
string = 'id'
Tells stats
to sort the modules by a given field. All of the sorting fields are allowed to be used as values for stats.modulesSort
. Use !
prefix in the value to reverse the sort order by a given field.
module.exports = {
//...
stats: {
modulesSort: 'size'
}
};
stats.moduleTrace
boolean = true
Tells stats
to show dependencies and the origin of warnings/errors. stats.moduleTrace
is available since webpack 2.5.0.
module.exports = {
//...
stats: {
moduleTrace: false
}
};
stats.outputPath
boolean = true
Tells stats
to show the outputPath
.
module.exports = {
//...
stats: {
outputPath: false
}
};
stats.performance
boolean = true
Tells stats
to show performance hint when the file size exceeds performance.maxAssetSize
.
module.exports = {
//...
stats: {
performance: false
}
};
stats.preset
string
boolean: false
Sets the preset for the type of information that gets displayed. It is useful for extending stats behaviours.
module.exports = {
//...
stats: {
preset: 'minimal'
}
};
Setting value of stats.preset
to false
tells webpack to use 'none'
stats preset.
stats.providedExports
boolean = false
Tells stats
to show the exports of the modules.
module.exports = {
//...
stats: {
providedExports: true
}
};
stats.errorsCount
boolean = true
Add errors count.
module.exports = {
//...
stats: {
errorsCount: false
}
};
stats.warningsCount
boolean = true
Add warnings count.
module.exports = {
//...
stats: {
warningsCount: false
}
};
stats.publicPath
boolean = true
Tells stats
to show the publicPath
.
module.exports = {
//...
stats: {
publicPath: false
}
};
stats.reasons
boolean = true
Tells stats
to add information about the reasons of why modules are included.
module.exports = {
//...
stats: {
reasons: false
}
};
stats.relatedAssets
boolean = false
Tells stats
whether to add information about assets that are related to other assets (like SourceMaps for assets).
module.exports = {
//...
stats: {
relatedAssets: true
}
};
stats.source
boolean = false
Tells stats
to add the source code of modules.
module.exports = {
//...
stats: {
source: true
}
};
stats.timings
boolean = true
Tells stats
to add the timing information.
module.exports = {
//...
stats: {
timings: false
}
};
stats.usedExports
boolean = false
Tells stats
whether to show which exports of a module are used.
module.exports = {
//...
stats: {
usedExports: true
}
};
stats.version
boolean = true
Tells stats
to add information about the webpack version used.
module.exports = {
//...
stats: {
version: false
}
};
stats.chunkGroupAuxiliary
boolean = true
Display auxiliary assets in chunk groups.
module.exports = {
//...
stats: {
chunkGroupAuxiliary: false
}
};
stats.chunkGroupChildren
boolean = true
Display children of the chunk groups (e.g. prefetched, preloaded chunks and assets).
module.exports = {
//...
stats: {
chunkGroupChildren: false
}
};
stats.chunkGroupMaxAssets
number
Limit of assets displayed in chunk groups.
module.exports = {
//...
stats: {
chunkGroupMaxAssets: 5
}
};
stats.warnings
boolean = true
Tells stats
to add warnings.
module.exports = {
//...
stats: {
warnings: false
}
};
stats.warningsFilter
array = []: string | RegExp | function (warning) => boolean
string
RegExp
function (warning) => boolean
Tells stats
to exclude the warnings that are matching given filters. This can be done with a string
, a RegExp
, a function
that is getting a warning as an argument and returns a boolean
. stats.warningsFilter
can be an array
of any of the above.
module.exports = {
//...
stats: {
warningsFilter: [
'filter',
/filter/,
(warning) => true
]
}
};
stats.chunkRelations
boolean = false
Tells stats
to display chunk parents, children and siblings.
For assetsSort
, chunksSort
and modulesSort
there are several possible fields that you can sort items by:
'id'
is the item's id;'name'
- a item's name that was assigned to it upon importing;'size'
- a size of item in bytes;'chunks'
- what chunks the item originates from (for example, if there are multiple subchunks for one chunk - the subchunks will be grouped together according to their main chunk);'errors'
- amount of errors in items;'warnings'
- amount of warnings in items;'failed'
- whether the item has failed compilation;'cacheable'
- whether the item is cacheable;'built'
- whether the asset has been built;'prefetched'
- whether the asset will be prefetched;'optional'
- whether the asset is optional;'identifier'
- identifier of the item;'index'
- item's processing index;'index2'
'profile'
'issuer'
- an identifier of the issuer;'issuerId'
- an id of the issuer;'issuerName'
- a name of the issuer;'issuerPath'
- a full issuer object. There's no real need to sort by this field;If you want to use one of the pre-defined behaviours e.g. 'minimal'
but still override one or more of the rules: specify the desired stats.preset
and add the customized or additional rules afterwards.
webpack.config.js
module.exports = {
//..
stats: {
preset: 'minimal',
moduleTrace: true,
errorDetails: true
}
};
experiments
boolean: false
experiments
option was introduced in webpack 5 to empower users with the ability to activate and try out experimental features.
Available options:
syncWebAssembly
: Support the old WebAssembly like in webpack 4asyncWebAssembly
: Support the new WebAssembly according to the updated specification, it makes a WebAssembly module an async moduletopLevelAwait
: Support the Top Level Await Stage 3 proposal, it makes the module an async module when await
is used on the top-leveloutputModule
: enables the use of output.module
configuration option and sets it to true
. Enables the use of output.libraryTarget
as 'module'
and sets it to 'module'
.layers
: Enable module and chunk layers.webpack.config.js
module.exports = {
//...
experiments: {
outputModule: true,
syncWebAssembly: true,
topLevelAwait: true,
asyncWebAssembly: true,
layers: true,
},
};
These are the remaining configuration options supported by webpack.
amd
object
boolean: false
Set the value of require.amd
or define.amd
. Setting amd
to false
will disable webpack's AMD support.
webpack.config.js
module.exports = {
//...
amd: {
jQuery: true
}
};
Certain popular modules written for AMD, most notably jQuery versions 1.7.0 to 1.9.1, will only register as an AMD module if the loader indicates it has taken special allowances for multiple versions being included on a page.
The allowances were the ability to restrict registrations to a specific version or to support different sandboxes with different defined modules.
This option allows you to set the key your module looks for to a truthy value. As it happens, the AMD support in webpack ignores the defined name anyways.
bail
boolean = false
Fail out on the first error instead of tolerating it. By default webpack will log these errors in red in the terminal, as well as the browser console when using HMR, but continue bundling. To enable it:
webpack.config.js
module.exports = {
//...
bail: true
};
This will force webpack to exit its bundling process.
cache
boolean
object
Cache the generated webpack modules and chunks to improve build speed. cache
is set to type: 'memory'
in development
mode and disabled in production
mode. cache: true
is an alias to cache: { type: 'memory' }
. To disable caching pass false
:
webpack.config.js
module.exports = {
//...
cache: false
};
cache.type
string: 'memory' | 'filesystem'
Sets the cache
type to either in memory or on the file system. The memory
option is straightforward, it tells webpack to store cache in memory and doesn't allow additional configuration:
webpack.config.js
module.exports = {
//...
cache: {
type: 'memory'
}
};
While setting cache.type
to filesystem
opens up more options for configuration.
cache.cacheDirectory
string
Base directory for the cache. Defaults to node_modules/.cache/webpack
.
cache.cacheDirectory
option is only available when cache.type
is set to filesystem
.
webpack.config.js
const path = require('path');
module.exports = {
//...
cache: {
type: 'filesystem',
cacheDirectory: path.resolve(__dirname, '.temp_cache')
}
};
cache.cacheLocation
string
Locations for the cache. Defaults to path.resolve(cache.cacheDirectory, cache.name)
.
webpack.config.js
const path = require('path');
module.exports = {
//...
cache: {
type: 'filesystem',
cacheLocation: path.resolve(__dirname, '.test_cache')
}
};
cache.buildDependencies
object
cache.buildDependencies
is an object of arrays of additional code dependencies for the build. webpack will use a hash of each of these items and all dependencies to invalidate the filesystem cache.
Defaults to webpack/lib
to get all dependencies of webpack.
module.exports = {
cache: {
buildDependencies: {
// This makes all dependencies of this file - build dependencies
config: [__filename]
// By default webpack and loaders are build dependencies
}
}
};
cache.managedPaths
[string] = ['./node_modules']
cache.managedPaths
is an array of package-manager only managed paths. webpack will avoid hashing and timestamping them, assume the version is unique and will use it as a snapshot (for both memory and filesystem cache).
cache.hashAlgorithm
string
Algorithm used the hash generation. See Node.js crypto for more details. Defaults to md4
.
cache.hashAlgorithm
option is only available when cache.type
is set to filesystem
.
webpack.config.js
module.exports = {
//...
cache: {
type: 'filesystem',
hashAlgorithm: 'md4'
}
};
cache.name
string
Name for the cache. Different names will lead to different coexisting caches. Defaults to ${config.name}-${config.mode}
. Using cache.name
makes sense when you have multiple configurations which should have independent caches.
cache.name
option is only available when cache.type
is set to filesystem
.
webpack.config.js
module.exports = {
//...
cache: {
type: 'filesystem',
name: 'AppBuildCache'
}
};
cache.store
string = 'pack': 'pack'
cache.store
tells webpack when to store data on the file system.
'pack'
: Store data when compiler is idle in a single file for all cached itemscache.store
option is only available when cache.type
is set to filesystem
.
webpack.config.js
module.exports = {
//...
cache: {
type: 'filesystem',
store: 'pack'
}
};
cache.version
string = ''
Version of the cache data. Different versions won't allow to reuse the cache and override existing content. Update the version when configuration changed in a way which doesn't allow to reuse cache. This will invalidate the cache.
cache.version
option is only available when cache.type
is set to filesystem
.
webpack.config.js
module.exports = {
//...
cache: {
type: 'filesystem',
version: 'your_version'
}
};
cache.idleTimeout
number = 10000
Time in milliseconds. cache.idleTimeout
denotes the time period after which the cache storing should happen.
webpack.config.js
module.exports = {
//..
cache: {
idleTimeout: 10000
}
};
cache.idleTimeoutForInitialStore
number = 0
Time in milliseconds. cache.idleTimeoutForInitialStore
is the time period after which the initial cache storing should happen.
webpack.config.js
module.exports = {
//..
cache: {
idleTimeoutForInitialStore: 0
}
};
ignoreWarnings
RegExp
function (WebpackError, Compilation) => boolean
{module?: RegExp, file?: RegExp, message?: RegExp}
Tells webpack to ignore specific warnings. This can be done with a RegExp
, a custom function
to select warnings based on the raw warning instance which is getting WebpackError
and Compilation
as arguments and returns a boolean
, an object
with the following properties:
file
: A RegExp to select the origin file for the warning.message
: A RegExp to select the warning message.module
: A RegExp to select the origin module for the warning.ignoreWarnings
can be an array
of any of the above.
module.exports = {
//...
ignoreWarnings: [
{
module: /module2\.js\?[34]/ // A RegExp
},
{
module: /[13]/,
message: /homepage/
},
(warning) => true
]
};
loader
object
Expose custom values into the loader context.
For example, you can define a new variable in the loader context:
webpack.config.js
module.exports = {
// ...
loader: {
answer: 42
}
};
Then use this.answer
to get its value in the loader:
custom-loader.js
module.exports = function (source) {
// ...
console.log(this.answer); // will log `42` here
return source;
};
parallelism
number = 100
Limit the number of parallel processed modules. Can be used to fine tune performance or to get more reliable profiling results.
profile
boolean
Capture a "profile" of the application, including statistics and hints, which can then be dissected using the Analyze tool.
recordsPath
string
Use this option to generate a JSON file containing webpack "records" β pieces of data used to store module identifiers across multiple builds. You can use this file to track how modules change between builds. To generate one, simply specify a location:
webpack.config.js
const path = require('path');
module.exports = {
//...
recordsPath: path.join(__dirname, 'records.json')
};
Records are particularly useful if you have a complex setup that leverages Code Splitting. The data can be used to ensure the split bundles are achieving the caching behavior you need.
recordsInputPath
string
Specify the file from which to read the last set of records. This can be used to rename a records file. See the example below.
recordsOutputPath
string
Specify where the records should be written. The following example shows how you might use this option in combination with recordsInputPath
to rename a records file:
webpack.config.js
const path = require('path');
module.exports = {
//...
recordsInputPath: path.join(__dirname, 'records.json'),
recordsOutputPath: path.join(__dirname, 'newRecords.json')
};
name
string
Name of the configuration. Used when loading multiple configurations.
webpack.config.js
module.exports = {
//...
name: 'admin-app'
};
Options for infrastructure level logging.
object = {}
string
Enable infrastructure logging output. Similar to stats.logging
option but for infrastructure. No default value is given.
Possible values:
'none'
- disable logging'error'
- errors only'warn'
- errors and warnings only'info'
- errors, warnings, and info messages'log'
- errors, warnings, info messages, log messages, groups, clears. Collapsed groups are displayed in a collapsed state.'verbose'
- log everything except debug and trace. Collapsed groups are displayed in expanded state.webpack.config.js
module.exports = {
//...
infrastructureLogging: {
level: 'info'
}
};
string
RegExp
function(name) => boolean
[string, RegExp, function(name) => boolean]
Enable debug information of specified loggers such as plugins or loaders. Similar to stats.loggingDebug
option but for infrastructure. No default value is given.
webpack.config.js
module.exports = {
//...
infrastructureLogging: {
level: 'info',
debug: [
'MyPlugin',
/MyPlugin/,
(name) => name.contains('MyPlugin')
]
}
};
snapshot
object
snapshot
options decide how the file system snapshots are created and invalidated.
webpack.config.js
const path = require('path');
module.exports = {
// ...
snapshot: {
managedPaths: [path.resolve(__dirname, '../node_modules')],
immutablePaths: [],
buildDependencies: {
hash: true,
timestamp: true
},
module: {
timestamp: true
},
resolve: {
timestamp: true
},
resolveBuildDependencies: {
hash: true,
timestamp: true
}
}
};
managedPaths
[string]
An array of paths that are managed by a package manager and can be trusted to not be modified otherwise.
immutablePaths
[string]
An array of paths that are managed by a package manager and contain a version or a hash in their paths so that all files are immutable.
buildDependencies
object = { hash boolean = true, timestamp boolean = true }
Snapshots for build dependencies when using the persistent cache.
hash
: Compare content hashes to determine invalidation (more expensive than timestamp
, but changes less often).timestamp
: Compare timestamps to determine invalidation.Both hash
and timestamp
are optional.
{ hash: true }
: Good for CI caching with a fresh checkout which doesn't keep timestamps and uses hashes.{ timestamp: true }
: Good for local development caching.{ timestamp: true, hash: true }
: Good for both cases mentioned above. Timestamps are compared first, which is cheap because webpack doesn't need to read files to compute their hashes. Content hashes will be compared only when timestamps are the same, which leads to a small performance hit for the initial build.module
object = {hash boolean = true, timestamp boolean = true}
Snapshots for building modules.
hash
: Compare content hashes to determine invalidation (more expensive than timestamp
, but changes less often).timestamp
: Compare timestamps to determine invalidation.resolve
object = {hash boolean = true, timestamp boolean = true}
Snapshots for resolving of requests.
hash
: Compare content hashes to determine invalidation (more expensive than timestamp
, but changes less often).timestamp
: Compare timestamps to determine invalidation.resolveBuildDependencies
object = {hash boolean = true, timestamp boolean = true}
Snapshots for resolving of build dependencies when using the persistent cache.
hash
: Compare content hashes to determine invalidation (more expensive than timestamp
, but changes less often).timestamp
: Compare timestamps to determine invalidation.