-
Notifications
You must be signed in to change notification settings - Fork 0
configuration
webpack is fed a configuration object. Depending on your usage of webpack there are two ways to pass this configuration object:
If you use the CLI it will read a file webpack.config.js (or the file passed by the --config option). This file should export the configuration object:
module.exports = {
// configuration
};If you use the node.js API you need to pass the configuration object as parameter:
webpack({
// configuration
}, callback);Very simple configuration object example:
{
context: __dirname + "/app",
entry: "./entry",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
}
}The base directory (absolute path!) for resolving the entry option. If output.pathinfo is set, the included pathinfo is shortened to this directory.
Default:
process.cwd()
The entry point for the bundle.
If you pass a string: The string is resolved to a module which is loaded upon startup.
If you pass an array: All modules are loaded upon startup. The last one is exported.
entry: ["./entry1", "./entry2"]If you pass an object: Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.
{
entry: {
page1: "./page1",
page2: ["./entry1", "./entry2"]
},
output: {
// Make sure to use [name] or [id] in output.filename
// when using multiple entry points
filename: "[name].bundle.js",
chunkFilename: "[id].bundle.js"
}
}Options affecting the output.
If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.
The output directory as absolute path.
[hash] is replaced by the hash of the compilation.
The filename of the entry chunk as relative path inside the output.path directory.
[name] is replaced by the name of the chunk.
[hash] is replaced by the hash of the compilation.
The filename of non-entry chunks as relative path inside the output.path directory.
[id] is replaced by the id of the chunk.
[hash] is replaced by the hash of the compilation.
[chunkhash] is replaced by the hash of the chunk.
The filename of named chunks as relative path inside the output.path directory.
[name] is replaced by the name of the chunk.
[hash] is replaced by the hash of the compilation.
The filename of the SourceMaps for the Javascript files. They are inside the output.path directory.
[file] is replaced by the filename of the Javascript file.
[id] is replaced by the id of the chunk.
[hash] is replaced by the hash of the compilation.
Default:
"[file].map"
The filename of the Hot Update Chunks. They are inside the output.path directory.
[id] is replaced by the id of the chunk.
[hash] is replaced by the hash of the compilation. (The last hash stored in the records)
Default:
"[id].[hash].hot-update.js"
The filename of the Hot Update Main File. It is inside the output.path directory.
[hash] is replaced by the hash of the compilation. (The last hash stored in the records)
Default:
"[hash].hot-update.json"
The output.path from the view of the javascript.
// Example
output: {
path: "/home/proj/public/assets",
publicPath: "/assets"
}
// Example CDN
output: {
path: "/home/proj/cdn/assets/[hash]",
publicPath: "http://cdn.example.com/assets/[hash]/"
}If you don't know the publicPath while compiling you can omit it and set
__webpack_public_path__on runtime.Example:
var scripts = document.getElementsByTagName("script"); var src = scripts[scripts.length - 1].getAttribute("src"); __webpack_public_path__ = src.substr(0, src.lastIndexOf("/") + 1);
The JSONP function used by webpack for asnyc loading of chunks.
A shorter function may reduce the filesize a bit. Use different identifier, when having multiple webpack instances on a single page.
Default:
"webpackJsonp"
The JSONP function used by webpack for async loading of hot update chunks.
Default:
"webpackHotUpdate"
Include comments with information about the modules.
require(/* ./test */23)
Do not use this in production.
Default:
false
If set, export the bundle as library. output.library is the name.
Use this, if you are writing a library and want to publish it as single file.
Which format to export the library:
"var" - Export by setting a variable: var Library = xxx (default)
"this" - Export by setting a property of this: this["Library"] = xxx
"commonjs" - Export by setting a property of exports: exports["Library"] = xxx
"commonjs2" - Export by setting module.exports: module.exports = xxx
"amd" - Export to AMD (optionally named)
"umd" - Export to AMD, CommonJS2 or as property in root
Default:
"var"
If output.library is not set, but output.libraryTarget is set to a value other that var, every property of the exported object is copied (Except amd, commonjs2 and umd).
Prefixes every line of the source in the bundle with this string.
Default: "\t"
Options affecting the normal modules (NormalModuleFactory)
A array of automatically applied loaders.
Each item can have these properties:
-
test: A condition that must be met -
exclude: A condition that must not be met -
include: A condition that must be met -
loader: A string of "!" separated loaders -
loaders: A array of loaders as string
A condition can be a RegExp, or a array of RegExps combined with "and".
See more: loaders
Syntax like module.loaders.
A array of applied pre and post loaders.
A RegExp or an array of RegExps. Don't parse files matching.
This can boost performance when ignoring big libraries.
The files are expected to have no call to require, define or similar. They are allowed to use exports and module.exports.
There are multiple options to configure the defaults for an automatically created context. We differentiate three types of automatically created contexts:
-
exprContext: An expression as dependency (i. e.require(expr)) -
wrappedContext: An expression plus pre- and/or surfixed string (i. e.require("./templates/" + expr)) -
unknownContext: Any other unparsable usage ofrequire(i. e.require)
Four options are possible for automatically created contexts:
-
request: The request for context. -
recursive: Subdirectories should be traversed. -
regExp: The RegExp for the expression. -
critical: This type of dependency should be consider as critical (emits a warning).
All options and defaults:
unknownContextRequest = ".", unknownContextRecursive = true, unknownContextRegExp = /^\.\/.*$/, unknownContextCritical = true
exprContextRequest = ".", exprContextRegExp = /^\.\/.*$/, exprContextRecursive = true, exprContextCritical = true
wrappedContextRegExp = /.*/, wrappedContextRecursive = true, wrappedContextCritical = false
Note:
module.wrappedContextRegExponly refers to the middle part of the full RegExp. The remaining is generated from prefix and surfix.
Example:
{
module: {
// Disable handling of unknown requires
unknownContextRegExp: /$^/,
unknownContextCritical: false,
// Warn for every expression in require
wrappedContextCritical: true
}
}Options affecting the resolving of modules.
Replace modules by other modules or paths.
Expected is a object with keys being module names. The value is the new path. It's similar to a replace but a bit more clever. If the the key ends with $ only the exact match (without the $) will be replaced.
If the value is a relative path it will be relative to the file containing the require.
Examples: Calling a require from /abc/entry.js with different alias settings.
alias: |
require("xyz") |
require("xyz/file.js") |
|---|---|---|
{} |
/abc/node_modules/xyz/index.js |
/abc/node_modules/xyz/file.js |
{ xyz: "/absolute/path/to/file.js" } |
/absolute/path/to/file.js |
error |
{ xyz$: "/absolute/path/to/file.js" } |
/absolute/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/dir/file.js |
{ xyz: "xyz/dir" } |
/abc/node_modules/xyz/dir/index.js |
/abc/node_modules/xyz/dir/file.js |
{ xyz$: "xyz/dir" } |
/abc/node_modules/xyz/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.
The directory that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.
An array of directory names to be resolved to the current directory as well as its ancestors, and searched for modules. This functions similarly to how node finds "node_modules" directories. For example, if the value is ["mydir"], webpack will look in "./mydir", "../mydir", "../../mydir", etc.
Default:
["web_modules", "node_modules"]
Note: Passing
"../someDir"isn't expected here. Just use a directory name, not a relative path.
A directory (or array of directories absolute paths), in which webpack should look for modules that weren't fount in resolve.root or resolve.modulesDirectories.
An array of extensions that should be used to resolve modules. For example, in order to discover CoffeeScript files, your array should contain the string "*.coffee".
Default:
["", ".webpack.js", ".web.js", ".js"]
IMPORTANT: Setting this option will override the default, meaning that webpack will no longer try to resolve modules using the default extensions. If you want modules that were required with their extension (e.g. require('./somefile.ext')) to be properly resolved, you must include an empty string in your array. Similarly, if you want modules that were required without extensions (e.g. require('underscore')) to be resolved to files with ".js" extensions, you must include ".js" in your array.
Check these fields in the package.json for suitable files.
Default:
["webpack", "browser", "web", "main"]
Check this field in the package.json for an object. Key-value-pairs are threaded as aliasing according to this spec
Not set by default
Example: "browser" to check the browser field.
Enable aggressive but unsafe caching for the resolving of a part of your files. Changes to cached paths may cause failure (in rare cases). An array of RegExps, only a RegExp or true (all files) is expected. If the resolved path matches, it'll be cached.
Default:
[]
Like resolve but for loaders.
// Default:
{
modulesDirectories: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"],
packageMains: ["webpackLoader", "webLoader", "loader", "main"]
}That's a resolveLoader only property.
It describes alternatives for the module name that are tried.
Default:
["*-webpack-loader", "*-web-loader", "*-loader", "*"]
Specify dependencies that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on output.libraryTarget.
As value an object, a string, a function, a RegExp and an array is accepted.
- string: An exact matched dependency becomes external. The same string is used as external dependency.
- object: If an dependency matches exactly a property of the object, the property value is used as dependency. The property value may contain a dependency type prefixed and separated with a space. If the property value is
truethe property name is used instead. If the property value isfalsethe externals test is aborted and the dependency is not external. See example below. - function:
function(context, request, callback(err, result))The function is called on each dependency. If a result is passed to the callback function this value is handled like a property value of an object (above bullet point). - RegExp: Every matched dependency becomes external. The request is also used as request for the external dependency.
- array: Multiple values of the scheme (recursive).
Example:
{
output: { libraryTarget: "commonjs" },
externals: [
{
a: false, // a is not external
b: true, // b is external (require("b"))
"./c": "c", // "./c" is external (require("c"))
"./d": "var d" // "./d" is external (d)
},
// Every non-relative module is external
// abc -> require("abc")
/^[a-z\-0-9]+$/,
function(context, request, callback) {
// Every module prefixed with "global-" becomes external
// "global-abc" -> abc
if(/^global-/.test(request))
return callback(null, "var " + request.substr(7));
callback();
},
"./e" // "./e" is external (require("./e"))
]
}| type | value | resulting import code |
|---|---|---|
| "var" | "abc" |
module.exports = abc; |
| "var" | "abc.def" |
module.exports = abc.def; |
| "this" | "abc" |
(function() { module.exports = this["abc"]; }()); |
| "this" | ["abc", "def"] |
(function() { module.exports = this["abc"]["def"]; }()); |
| "commonjs" | "abc" |
module.exports = require("abc"); |
| "commonjs" | ["abc", "def"] |
module.exports = require("abc").def; |
| "amd" | "abc" |
define(["abc"], function(X) { module.exports = X; }) |
| "umd" | "abc" |
everything above |
Enforcing amd or umd in a external value will break if not compiling as amd/umd target.
Note: If using
umdyou can specify an object as external value with propertycommonjs,commonjs2,amdandrootto set different values for each import kind.
-
"web"Compile for usage in a browser-like environment (default) -
"webworker"Compile as WebWorker -
"node"Compile for usage in a node.js-like environment (userequireto load chunks) -
"async-node"Compile for usage in a node.js-like environment (usefsandvmto load chunks async) -
"node-webkit"Compile for usage in webkit, uses jsonp chunk loading but also supports native node.js modules plus require("nw.gui").
Report the first error at a hard error instead of tolerating it.
Capture timing information for each module.
Hint: Use the analyze tool to visualize it.
Cache generated modules and chunks to improve performance for multiple incremental builds.
Enter watch mode, which rebuilds on file change.
Only use it with the node.js javascript api webpack(options, fn).
Delay the rebuilt after the first change. Value is a time in ms.
Default: 200
Switch loaders to debug mode.
Choose a developer tool to enhance debugging.
eval - Each module is executed with eval and //@ sourceURL.
source-map - A SourceMap is emitted. See also output.sourceMapFilename.
inline-source-map - A SourceMap is added as DataUrl to the Javascript file.
eval-source-map - Each module is executed with eval and a SourceMap is added as DataUrl to the eval.
Prefixing @, # or #@ will enforce a pragma style.
Include polyfills or mocks for various node stuff:
-
console:trueorfalse -
global:trueorfalse -
process:true,"mock"orfalse -
buffer:true,"mock"orfalse -
__filename:true(real filename),"mock"("/index.js") orfalse -
__dirname:true(real dirname),"mock"("/") orfalse -
<node buildin>:true,"mock"orfalse
// Default:
{
console: false,
process: true,
global: true,
buffer: true,
__filename: "mock",
__dirname: "mock"
}Set the value of require.amd and define.amd.
Example: amd: { jQuery: true } (for old 1.x AMD versions of jquery)
Custom values available in the loader context.
Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks.
An absolute path is excepted. recordsPath is used for recordsInputPath and recordsOutputPath if they left undefined.
This is required, when using Hot Code Replacement between multiple calls to the compiler.
Add additional plugins to the compiler.