Skip to content
This repository was archived by the owner on Mar 22, 2019. It is now read-only.

configuration.cn

e-cloud edited this page Jul 12, 2016 · 2 revisions

webpack is fed a configuration object. Depending on your usage of webpack there are two ways to pass this configuration object:

webpack 以配置对象驱动。根据你的使用需要,配置对象的传入方式有两种。

CLI

命令行

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:

如果你使用CLI,它会读取webpack.config.js或者通过选项--config声明的文件。这个文件必须输出配置对象。

module.exports = {
	// configuration
};

node.js API

If you use the node.js API you need to pass the configuration object as parameter:

如果你使用node.js API,你需要将配置对象作为参数传入。

webpack({
	// configuration
}, callback);

multiple configurations

In both cases you can also use an array of configurations, which are processed in parallel. They share filesystem cache and watchers so this is more efficent than calling webpack multiple times.

多个配置

两种用例都可以传入一组配置,会被并行处理。它们共享文件系统的缓存和监视器,因此相对于多次调用webpack,这种方式更高效。

configuration object content

配置对象的内容

Hint: Keep in mind that you don't need to write pure JSON into the configuration. Use any JavaScript you want. It's just a node.js module...

提示:记住你不需要在配置里写纯粹的JSON格式的数据。用任何你想用的Javascript代码,他只是一个 node.js 的模块而已...

Very simple configuration object example:

非常简单的配置对象的例子:

{
	context: __dirname + "/app",
	entry: "./entry",
	output: {
		path: __dirname + "/dist",
		filename: "bundle.js"
	}
}

context

The base directory (absolute path!) for resolving the entry option. If output.pathinfo is set, the included pathinfo is shortened to this directory.

用来解析 entry 选项的根目录(绝对路径)。如果设置了output.pathinfo,引入的路径信息会以此目录为根。

Default: process.cwd()

entry

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"
	}
}

NOTE: It is not possible to configure other options specific to entry points. If you need entry point specific configuration you need to use multiple configurations.

注意: 对特定入口点配置其他选项是不可能的。如果你需要对入口点进行特定配置,你需要使用多个配置.

output

Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.

影响编译的输出的选项。output选项告诉webpack怎么将编译后的文件写入磁盘。注意,虽然可以有多个entry入口点,只能指定一个output配置对象

If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurrenceOrderPlugin or recordsPath.

如果要使用任何hash标记([hash][chunkhash]),请确保模块的排序是一致的。使用OccurenceOrderPlugin 或者 recordsPath

output.filename

Specifies the name of each output file on disk. You must not specify an absolute path here! The output.path option determines the location on disk the files are written to, filename is used solely for naming the individual files.

指定磁盘上每个输出文件的命名。你在这不能指定一个绝对路径。output.path选项用来决定文件写入磁盘的位置,filename只是用来命名个体文件。

single entry

{
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/build'
  }
}

// writes to disk: ./build/bundle.js

multiple entries 多个入口

If your configuration creates more than a single "chunk" (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions below to ensure that each file has a unique name.

如果你的配置创建不止一个单独“分块”(如使用多个入口点或使用了CommonsChunkPlugin类的插件),你需要使用下面的可替换符来保证每个文件名唯一。

[name] is replaced by the name of the chunk.

[name] 被替换为分块名称

[hash] is replaced by the hash of the compilation. [hash] 被替换为整个编译的hash

[chunkhash] is replaced by the hash of the chunk. [chunkhash] 被替换为分块的hash

{
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/build'
  }
}

// writes to disk: ./build/app.js, ./build/search.js

output.path

The output directory as absolute path (required).

输出目录,绝对路径(必须存在)

[hash] is replaced by the hash of the compilation.

[hash]被替换为整个编译的hash

output.publicPath

The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed <script> or <link> tags or reference assets like images, publicPath is used as the href or url() to the file when it's different than their location on disk (as specified by path). This can be helpful when you want to host some or all output files on a different domain or on a CDN. The Webpack Dev Server also uses this to determine the path where the output files are expected to be served from. As with path you can use the [hash] substitution for a better caching profile.

publicPath指定了浏览器引用的输出文件的URL根地址。当某些加载的文件嵌入了<script><link> 或者引用了资源如图片,publicPath 会作为hrefurl()指向的文件的根路径,与文件的磁盘路径(由path指定)相异。当你想将部分或所有输出文件放到某个域名或CDN上,这选项会很有用。webpack-dev-server也使用这个选项去决定输出文件期望的访问路径。跟path一样,你可以使用[hash]可替换符来适用更好的缓存方案。

config.js

output: {
	path: "/home/proj/public/assets",
	publicPath: "/assets/"
}

index.html

<head>
  <link href="/assets/spinner.gif"/>
</head>

And a more complicated example of using a CDN and hashes for assets.

一个更复杂的例子,使用了CDN和资源hash

config.js

output: {
	path: "/home/proj/cdn/assets/[hash]",
	publicPath: "http://cdn.example.com/assets/[hash]/"
}

Note: In cases when the eventual publicPath of output files isn't known at compile time, it can be left blank and set dynamically at runtime in the entry point file.

注意: 某些情况下,当输出文件最终的publicPath在编译时尚不可知,可以留空并于运行时在入口点文件动态设置。

If you don't know the publicPath while compiling you can omit it and set __webpack_public_path__ on your entry point.

如果编译时不知道publicPath,你可以忽略他并在入口点设置__webpack_public_path__

 __webpack_public_path__ = myRuntimePublicPath

// rest of your application entry

output.chunkFilename

The filename of non-entry chunks as relative path inside the output.path directory.

非入口分块的文件名,相对于output.path指定目录

[id] is replaced by the id of the chunk. [id] 被替换为分块id

[name] is replaced by the name of the chunk (or with the id when the chunk has no name). [name] 被替换为分块名称(当分块无名称时则是分块id)

[hash] is replaced by the hash of the compilation. [hash] 被替换为整个编译的hash

[chunkhash] is replaced by the hash of the chunk. [chunkhash] 被替换为分块的hash

output.sourceMapFilename

The filename of the SourceMaps for the JavaScript files. They are inside the output.path directory.

javascript文件对应的sourcemap的文件名。位于output.path目录

[file] is replaced by the filename of the JavaScript file. [file] 被替换为javascript文件的名名称

[id] is replaced by the id of the chunk. [id] 被替换为分块id

[hash] is replaced by the hash of the compilation. [hash] 被替换为整个编译的hash

Default: "[file].map"

output.devtoolModuleFilenameTemplate

Filename template string of function for the sources array in a generated SourceMap.

处理生成的sourcemap内sources数组的函数用到的文件名字符串模板

[resource] is replaced by the path used by Webpack to resolve the file, including the query params to the rightmost loader (if any). [resource] 被替换为webpack用来解析文件的路径,包括最后一个loader的查询参数(如果有的话)

[resource-path] is the same as [resource] but without the loader query params. [resource-path][resource]相同但没有查询参数

[loaders] is the list of loaders and params up to the name of the rightmost loader (only explict loaders). [loaders] loader+查询参数的字符串直到最右边的loader(只针对显式指定的loader)

[all-loaders] is the list of loaders and params up to the name of the rightmost loader (including automatic loaders). [all-loaders] loader+查询参数的字符串直到最右边的loader(包括自动匹配的loader)

[id] is replaced by the id of the module. [id] 被替换为模块的id

[hash] is replaced by the hash of the module identifier. [hash] is 被替换为模块标识的hash

[absolute-resource-path] is replaced with the absolute filename. [absolute-resource-path] 被替换为绝对路径

Default (devtool=[inline-]source-map): "webpack:///[resource-path]" Default (devtool=eval): "webpack:///[resource-path]?[loaders]" Default (devtool=eval-source-map): "webpack:///[resource-path]?[hash]"

Can also be defined as a function instead of a string template. The function will accept an info object parameter which exposes the following properties:

也可以定义成一个函数而不是一个字符串模板。这个函数会接收一个包含下列属性的info参数:

  • identifier
  • shortIdentifier
  • resource
  • resourcePath
  • absoluteResourcePath
  • allLoaders
  • query
  • moduleId
  • hash

output.devtoolFallbackModuleFilenameTemplate

Similar to output.devtoolModuleFilenameTemplate, but used in the case of duplicate module identifiers.

类似于output.devtoolModuleFilenameTemplate,但用于模块标识重复的情况下

Default: "webpack:///[resourcePath]?[hash]"

output.devtoolLineToLine

Enable line to line mapped mode for all/specified modules. Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. It's a performance optimization. Only use it if your performance needs to be better and you are sure that input lines match which generated lines.

对所有或指定模块开启行到行映射模式。行到行映射模式使用了一种简单的sourcemap,生成的文件的每一行都会被映射到源文件的对应行。这是一种性能优化。仅当需要更佳性能时使用,而且你确认输入文件的行匹配到生成文件的行

true enables it for all modules (not recommended) true: 为所有模块开启此特性(不推荐)

An object {test, include, exclude} similar to module.loaders enables it for specific files.

module.loaders相似的对象{test, include, exclude}:为特定模块开启此特性。

Default: disabled

output.hotUpdateChunkFilename

The filename of the Hot Update Chunks. They are inside the output.path directory.

热更新分块的文件名,位于output.path目录

[id] is replaced by the id of the chunk. [id] 被替换为分块id

[hash] is replaced by the hash of the compilation. (The last hash stored in the records) [hash] 被替换为整个编译的hash(存在记录里的最后一个hash)

Default: "[id].[hash].hot-update.js"

output.hotUpdateMainFilename

The filename of the Hot Update Main File. It is inside the output.path directory.

热更新主文件的文件名,位于output.path目录

[hash] is replaced by the hash of the compilation. (The last hash stored in the records) [hash] 被替换为整个编译的hash(存在记录里的最后一个hash)

Default: "[hash].hot-update.json"

output.jsonpFunction

The JSONP function used by webpack for asnyc loading of chunks. webpack用来异步加载分块的JSONP函数

A shorter function may reduce the filesize a bit. Use different identifier, when having multiple webpack instances on a single page.

一个更短小的函数可能减少一点文件尺寸。当在一个页面上有多个webpack实例时,使用不同的标识符。

Default: "webpackJsonp"

output.hotUpdateFunction

The JSONP function used by webpack for async loading of hot update chunks. webpack用来异步加载热更新分块的JSONP函数

Default: "webpackHotUpdate"

output.pathinfo

Include comments with information about the modules. 插入有关模块信息的注释

require(/* ./test */23)

Do not use this in production. 不要在生成环境使用

Default: false

output.library

If set, export the bundle as library. output.library is the name.

如果设置了的话,将打包结果导出成一个库,output.library的值就是库名称

Use this, if you are writing a library and want to publish it as single file. 当你在写一个库并想以单个文件发布,使用这个配置。

output.libraryTarget

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 - set the name via the library option)

"umd" - Export to AMD, CommonJS2 or as property in root

"var" - 通过设置一个变量导出: var Library = xxx(默认)

"this" - 通过设置this的属性导出: this["Library"] = xxx

"commonjs" - 通过设置exports的属性导出: exports["Library"] = xxx

"commonjs2" - 通过设置module.exports的属性导出: module.exports = xxx

"amd" - 以AMD规范包装导出(命名可选 - 通过library选项设置)

"umd" - 以UMD规范包装导出,兼容AMD, CommonJS2 或者全局暴露形式

Default: "var"

If output.library is not set, but output.libraryTarget is set to a value other than var, every property of the exported object is copied (Except amd, commonjs2 and umd).

如果output.library没有设置,但output.libraryTarget又设置成thiscommonjs,输出对象的每个属性都会被复制。[不太明白]

output.umdNamedDefine

If output.libraryTarget is set to umd and output.library is set, setting this to true will name the AMD module.

如果设置了output.libraryTarget,也设置了output.library,这选项设置成 true 会给AMD模块命名

output.sourcePrefix

Prefixes every line of the source in the bundle with this string.

用选项值为打包结果中每一行代码添加前缀。

Default: "\t"

output.crossOriginLoading

This option enables cross-origin loading of chunks. 此选项开启跨域加载分块

Possible values are: 可选值为:

false - Disable cross-origin loading. false - 关闭跨域加载

"anonymous" - Cross-origin loading is enabled. When using anonymous no credentials will be sent with the request. "anonymous" - 开启跨域加载。请求不会携带credentials

"use-credentials" - Cross-origin loading is enabled and credentials will be send with the request. "use-credentials" - 开启跨域加载。请求不会携带credentials

For more information on cross-origin loading see MDN 关于跨域加载的更多信息参见 MDN

Default: false

module

Options affecting the normal modules (NormalModuleFactory) 影响普通模块(NormalModuleFactory)的选项。

module.loaders

An array of automatically applied loaders. 自动启用的loader数组

Each item can have these properties: 每一项元素可含有以下属性:

  • test: A condition that must be met

  • exclude: A condition that must not be met [none]* include: A condition that must be met

  • loader: A string of "!" separated loaders

  • loaders: An array of loaders as string

  • test: 必须设置的约束条件

  • exclude: 必须不匹配的约束条件

  • include: 必须匹配的约束条件

  • loader: 以分割的loader组合

  • loaders: 字符串数组形式的loader组合

A condition may be a RegExp (tested against absolute path), a string containing the absolute path, a function(absPath): bool, or an array of one of these combined with "and".

约束条件可以是一个RegExp(测试对象为绝对路径),一个包含绝对路径的string,一个形如function(absPath): bool的函数,或者一个上述形式的数组组合(会以“and”结合判断)

See more: loaders 更多参见:loaders

IMPORTANT: The loaders here are resolved relative to the resource which they are applied to. This means they are not resolved relative to the configuration file. If you have loaders installed from npm and your node_modules folder is not in a parent folder of all source files, webpack cannot find the loader. You need to add the node_modules folder as absolute path to the resolveLoader.root option. (resolveLoader: { root: path.join(__dirname, "node_modules") })

重要信息: 这里的加载器的解析寻找会相对于所应用的资源的路径。也就是说,它们不会以相对于配置文件的路径进行解析寻找。如果从npm安装了 loader,而且node_modules没有位于所有源文件的父级目录,webpack会找不到loader。你需要添加node_modules目录的绝对路径到resolveLoader.root选项。(resolveLoader: { root: path.join(__dirname, "node_modules") })

Example:

module: {
  loaders: [
    {
      // "test" is commonly used to match the file extension
      test: /\.jsx$/,

      // "include" is commonly used to match the directories
      include: [
        path.resolve(__dirname, "app/src"),
        path.resolve(__dirname, "app/test")
      ],

      // "exclude" should be used to exclude exceptions
      // try to prefer "include" when possible

      // the "loader"
      loader: "babel-loader" // or "babel" because webpack adds the '-loader' automatically
    }
  ]
}

module.preLoaders, module.postLoaders

Syntax like module.loaders. 用法类似module.loaders

An array of applied pre and post loaders.

使用到的前置与后置loader的数组。

module.noParse

A RegExp or an array of RegExps. Don't parse files matching.

一个RegExp或者一个RegExp的数组。不解析匹配的文件。

It's matched against the full resolved request.

所有解析请求都会进行匹配。

This can boost the 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.

这些文件应当没有require, define等方法的调用,但运行使用exportsmodule.exports

automatically created contexts defaults module.xxxContextXxx

自动创建的默认上下文 module.xxxContextXxx

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 suffixed string (i. e. require("./templates/" + expr))

  • unknownContext: Any other unparsable usage of require (i. e. require)

  • exprContext: 表达式作为依赖 (i. e. require(expr))

  • wrappedContext: 表达式加上了前缀或后缀字符串(i. e. require("./templates/" + expr))

  • unknownContext: 其他无法解析的 require 使用情形(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).

  • request: 请求上下文

  • recursive: 应遍历子目录

  • regExp: 表达式的正则匹配

  • critical: 被视为非法的依赖类型(抛出警告)

All options and defaults: 所有选项及默认值:

unknownContextRequest = ".", unknownContextRecursive = true, unknownContextRegExp = /^\.\/.*$/, unknownContextCritical = true

exprContextRequest = ".", exprContextRegExp = /^\.\/.*$/, exprContextRecursive = true, exprContextCritical = true

wrappedContextRegExp = /.*/, wrappedContextRecursive = true, wrappedContextCritical = false

Note: module.wrappedContextRegExp only refers to the middle part of the full RegExp. The remaining is generated from prefix and surfix.

注意: module.wrappedContextRegExp 只是代表完整正则的中间部分,剩余部分从前缀和后缀生成。

Example:

{
  module: {
	// Disable handling of unknown requires
	unknownContextRegExp: /$^/,
	unknownContextCritical: false,

	// Disable handling of requires with a single expression
	exprContextRegExp: /$^/,
	exprContextCritical: false,

	// Warn for every expression in require
	wrappedContextCritical: true
  }
}

resolve

Options affecting the resolving of modules. 影响解析模块的选项

resolve.alias

Replace modules with other modules or paths.

使用其他模块或路径替换目标模块。

Expected an 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.

如果属性值是一个相对路径,会相对于使用require的文件。

Examples: Calling a require from /abc/entry.js with different alias settings.

示例:使用不同的alias设定,在/abc/entry.js调用require

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 /abc/node_modules/xyz/file.js
{ xyz$: "/absolute/path/to/file.js" } /absolute/path/to/file.js error
{ xyz: "./dir/file.js" } /abc/dir/file.js /abc/node_modules/xyz/file.js
{ xyz$: "./dir/file.js" } /abc/dir/file.js error
{ 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.

如果package.json中定义了main的话,index.js可能会解析成另外一个文件

/abc/node_modules may resolve in /node_modules too.

/abc/node_modules也可能解析到/node_modules

resolve.root

The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

存放模块的目录(绝对路径)。也可以是一组目录。此设定选项应当用来给路径解析引擎添加额外的搜寻目录。

It must be an absolute path! Don't pass something like ./app/modules.

必须绝对路径!不要传入这样的路径./app/modules

Example: 样例:

var path = require('path');

// ...
resolve: {
  root: [
    path.resolve('./app/modules'),
    path.resolve('./vendor/modules')
  ]
}

resolve.modulesDirectories

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.

基于当前目录及其父级目录解析的一组目录名。这跟node寻找node_modules相似。例如,如果值为["mydir"],webpack会在"./mydir", "../mydir", "../../mydir"等目录搜索模块。

Default: ["web_modules", "node_modules"]

Note: Passing "../someDir", "app", "." or an absolute path isn't necessary here. Just use a directory name, not a path. Use only if you expect to have a hierarchy within these folders. Otherwise you may want to use the resolve.root option instead.

注意:这里不必传入"../someDir", "app", "."或一个绝对路径。只消一目录名,非路径也。仅当你有一套模块体系在此类文件夹内。否则,也许你要使用resolve.root 选项。

resolve.fallback

A directory (or array of directories absolute paths), in which webpack should look for modules that weren't found in resolve.root or resolve.modulesDirectories.

当webpack在resolve.root or resolve.modulesDirectories中找不到所需的模块时,用来寻找模块的后备目录(或者一组目录(绝对路径))

resolve.extensions

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".

用来解析模块的一组文件扩展名。例如,为了发现CoffeeScript文件,数组里应当含有".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.

重要信息: 设置此选项会覆盖默认配置,这意味着webpack不再尝试解析使用默认扩展名的模块。如果你想引用到的带有扩展名的模块被正确解析,你必须在数组里包含一个空字符串。同理,如果你想引用到的不带扩展名的模块(如require('underscore'))被正确解析成带".js"扩展名的文件,必须在数组里包含".js"

resolve.packageMains

Check these fields in the package.json for suitable files.

package.json检查相应属性,以找到模块入口文件。

Default: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"]

Note: This option has been changed to resolve.mainFields in webpack 2. 注意: 这个选项在 webpack 2 中被改名为resolve.mainFields

resolve.packageAlias

Check this field in the package.json for an object. Key-value-pairs are threaded as aliasing according to this spec

package.json检查相应属性对象,键值对会被视为模块引用别名,根据此规范

Not set by default

默认为空

Example: "browser" to check the browser field.

例如: "browser"会检查browser属性

resolve.unsafeCache

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.

开启激进但不安全的缓存机制来解析部分文件。缓存了路径的文件的修改可能引致失败(罕见案例下)。只允许一组RegExps,一个RegExpstrue(即所有文件)。如果匹配到解析的路径,会被缓存下来。

Default: []

resolveLoader

Like resolve but for loaders. 像resolve选项,但针对loader。

// 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"]
}

Note that you can use alias here and other features familiar from resolve. For example { txt: 'raw-loader' } would shim txt!templates/demo.txt to use raw-loader.

要注意到,在这你可以使用aliasresolve里其他相似特性。如{ txt: 'raw-loader' } 会指导raw-loader处理txt!templates/demo.txt

resolveLoader.moduleTemplates

That's a resolveLoader only property. 这是resolveLoader独有属性。

It describes alternatives for the module name that are tried.

其定义了尝试解析loader模块的候选方案。

Default: ["*-webpack-loader", "*-web-loader", "*-loader", "*"]

externals [整个小节翻译不太顺]

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.

指定不应由webpack来解析的依赖,但应当是成为打包结果的依赖。依赖的类型取决于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 true the property name is used instead. If the property value is false the externals test is aborted and the dependency is not external. See example below.

  • 对象:如果依赖名完全匹配对象的一个属性名,那么该属性值会用作依赖名。属性值可能包含带类型前缀并以空格分隔的依赖。如果属性值为true,则使用属性名作为依赖。如果属性值为false,外部依赖测试中断,且不是外部依赖。见下例。

  • 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).

  • 函数function(context, request, callback(err, result))每个依赖都会调用此函数,如果回调函数被传入结果值,此值会像对象的属性值(上面的列表项)一样被处理

  • RegExp: Every matched dependency becomes external. The matched text is used as the request for the external dependency. Because the request is the exact code used to generate the external code hook, if you are matching a commonjs package (e.g. '../some/package.js'), instead use the function external strategy. You can import the package via callback(null, "require('" + request + "')", which generates a module.exports = require('../some/package.js');, using require outside of webpack context.

  • 正则:每个匹配的依赖会变成外部依赖。匹配的文本被用作外部依赖的request参数。因为request才是用来生成外部代码的钩子,如果你正用于匹配一个commonjs包(如'../some/package.js'),转而使用函数策略处理外部依赖吧。你可以通过callback(null, "require('" + request + "')"导入包,会导致生成module.exports = require('../some/package.js');,在webpack上下文之外使用require。

  • 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.

如果外部依赖没有编译成amd/umd形式,强制外部依赖使用amdumd会导致崩溃。

Note: If using umd you can specify an object as external value with property commonjs, commonjs2, amd and root to set different values for each import kind.

注意:如果使用umd,你可以指定带有commonjs, commonjs2, amd and root 属性的对象作为外部值,为每种引入类型设置不同值

target

  • "web" Compile for usage in a browser-like environment (default)

  • "webworker" Compile as WebWorker

  • "node" Compile for usage in a node.js-like environment (use require to load chunks)

  • "async-node" Compile for usage in a node.js-like environment (use fs and vm to load chunks async)

  • "node-webkit" Compile for usage in webkit, uses jsonp chunk loading but also supports build in node.js modules plus require("nw.gui") (experimental)

  • "electron" Compile for usage in Electron – supports require-ing Electron-specific modules.

  • "electron-renderer" Compile for electron renderer process, provide a target using JsonpTemplatePlugin, FunctionModulePlugin for browser environment and NodeTargetPlugin and ExternalsPlugin for commonjs and electron bulit-in modules. Note: need webpack >= 1.12.15.

  • "web" 编译以用于泛浏览器环境(默认)

  • "webworker" 编译成webworker

  • "node" 编译以用于泛node.js环境(使用require加载分块)

  • "async-node" 编译以用于泛node.js环境(使用fsvm异步加载分块)

  • "node-webkit" 编译以用于 webkit,使用JSONP加载分块,但同样支持node.js内置模块和require("nw.gui")(实验性)

  • "electron" 编译以用于 Electron - 支持requireElectron特有模块

  • "electron-renderer" 为 electron 渲染进程进行编译。提供了使用JsonpTemplatePluginFunctionModulePlugin的面向浏览器环境的构建目标,以及使用NodeTargetPluginExternalsPlugin的面向 commonjs 与 electron 内置模块的构建目标

bail

Report the first error as a hard error instead of tolerating it.

将出现的第一个错误报告成严重错误,而不是忽略它。

profile

Capture timing information for each module.

为每个模块捕捉时序信息。

Hint: Use the analyze tool to visualize it. --json or stats.toJson() will give you the stats as JSON.

提示: 使用 分析工具 来可视化分析. --jsonstats.toJson() 会输出JSON格式的统计信息。

cache

Cache generated modules and chunks to improve performance for multiple incremental builds.

缓存生成的模块与分块来提高增量构建的性能。

This is enabled by default in watch mode.

监视模式下自动开启。

You can pass false to disable it.

可以传入false来关闭

You can pass an object to enable it and let webpack use the passed object as cache. This way you can share the cache object between multiple compiler calls. Note: Don't share the cache between calls with different options.

你可以传入一个对象来开启,并让webpack来用作缓存对象。这样,你可以在多次编译调用间共享缓存。注意:使用不同的配置时不要共享缓存对象。

debug

Switch loaders to debug mode.

让loader切换至调试模式。

devtool

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.

hidden-source-map - Same as source-map, but doesn't add a reference comment to the bundle.

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.

cheap-source-map - A SourceMap without column-mappings. SourceMaps from loaders are not used.

cheap-module-source-map - A SourceMap without column-mappings. SourceMaps from loaders are simplified to a single mapping per line.

eval - 每个模块都会使用 eval 执行 并使用 //@ sourceURL

source-map - 生成一份sourcemap. 参见 output.sourceMapFilename

hidden-source-map - 跟 source-map一样, 但打包文件里没有引用sourcemap的注释

inline-source-map - sourcemap以DataURL的形式注入bundle

eval-source-map - 每个模块都会使用 eval 执行,而且 sourcemap以DataURL的形式被eval执行

cheap-source-map - 没有列映射的sourcemap. 不会用到loader生成的sourcemap.

cheap-module-source-map - 没有列映射的sourcemap。loader生成的sourcemap会被简化为只有行映射

Prefixing @, # or #@ will enforce a pragma style. (Defaults to @ in webpack@1 and # in webpack@2; using # is recommended)

@, ##@为前缀会强制使用pragma风格的sourcemap。(webpack@1默认使用@webpack@2默认为#;推荐使用#

Combinations are possible. hidden, inline, eval and pragma style are exclusive. 组合使用是可以的,只允许hidden, inline, eval 和 pragma 风格

i. e. cheap-module-inline-source-map, cheap-eval-source-map, #@source-map

Hint: If your modules already contain SourceMaps you'll need to use the source-map-loader to merge it with the emitted SourceMap.

提示:如果模块已经包含sourcemap,你需要使用source-map-loader来与其他sourcemap合并

devtool build speed rebuild speed production supported quality
eval +++ +++ no generated code
cheap-eval-source-map + ++ no transformed code (lines only)
cheap-source-map + o yes transformed code (lines only)
cheap-module-eval-source-map o ++ no original source (lines only)
cheap-module-source-map o - yes original source (lines only)
eval-source-map -- + no original source
source-map -- -- yes original source

Example:

{
	devtool: "#inline-source-map"
}
// =>
//# sourceMappingURL=...

Note: With the next major version the default for -d will change to cheap-module-eval-source-map

注意:下一个大版本更新时-d的默认值会改为cheap-module-source-map

devServer

Can be used to configure the behaviour of webpack-dev-server when the webpack config is passed to webpack-dev-server CLI.

webpack-dev-server命令行被传入webpack配置,此选项可用来配置webpack-dev-server的行为。

Example:

{
	devServer: {
		contentBase: "./build",
	}
}

node

Include polyfills or mocks for various node stuff:

对node.js不同对象的 polyfill 或 mock

  • console: true or false

  • global: true or false

  • process: true, "mock" or false

  • Buffer: true or false

  • __filename: true (real filename relative to the context option), "mock" ("/index.js") or false (normal node __dirname)

  • __dirname: true (real dirname relative to the context option), "mock" ("/") or false (normal node __dirname)

  • <node buildin>: true, "mock", "empty" or false

  • console: truefalse

  • global: truefalse

  • process: true, "mock"false

  • Buffer: truefalse

  • __filename: true (相对于 context 选项的实际文件名), "mock" ("/index.js") 或 false(正常的 __filename)

  • __dirname: true (相对于 context 选项的实际文件名), "mock" ("/") 或 false(正常的__dirname)

  • <node buildin>: true, "mock", "empty"false

// Default:
{
	console: false,
	global: true,
	process: true,
	Buffer: true,
	__filename: "mock",
	__dirname: "mock",
	setImmediate: true
}

amd

Set the value of require.amd and define.amd.

设置require.amddefine.amd的值

Example: amd: { jQuery: true } (for old 1.x AMD versions of jquery) 如: amd: { jQuery: true } (适应旧版 1.x AMD 版本的 jquery)

loader

Custom values available in the loader context.

可用于loader上下文的自定义值

recordsPath, recordsInputPath, recordsOutputPath

Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks.

存储编译状态数据到 json 文件,或从 json 文件加载编译状态数据。这会导致module和chunk有持久不变的id

An absolute path is expected. recordsPath is used for recordsInputPath and recordsOutputPath if they left undefined.

需要绝对路径。 如果 recordsInputPathrecordsOutputPath 没有定义的话,recordsPath 将代指两者。

This is required, when using Hot Code Replacement between multiple calls to the compiler.

当编译器多次被调用且使用代码热替换时,这些选项是需要的。

plugins

Add additional plugins to the compiler.

给编译器添加额外的插件。

Clone this wiki locally