webpack入门(四)webpack的api 2 module

接着介绍webpack的module。

module

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

module.loaders

An array of automatically applied loaders.  一个自动装载机(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
  • loaders: An array of loaders as string  loaders的字符串数组

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

可能有一项是正则表达式(测试绝对路径),包含绝对路径的字符串,一个函数 function(absPath): bool,或者一个数组,用"and"结合

See more: loaders

IMPORTANT: The loaders here are resolved relative to the resource which they are applied to. This means they are not resolved relative the 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.rootoption. (resolveLoader: { root: path.join(__dirname, "node_modules") })

这里的loader解决了他们应用相关的资源,这意味着他们不需要解决配置文件的相关。如果你用npm安装loaders,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"
}
]

text用于匹配文件的拓展名,include常用于匹配路径。试着喜欢用“include”。loader是loader的名字

module.preLoadersmodule.postLoaders

Syntax like module.loaders.    语法跟module.loaders很像

An array of applied pre and post loaders.   前置和后置装载的数组loaders

module.noParse

A RegExp or an array of RegExps. Don’t parse files matching.  一个正则表达式或者一组正则,不会匹配到的路径

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 requiredefine or similar. They are allowed to use exports and module.exports.

该文件预计不可调用require,define或者其他类似的东西,不过可以用exports和modulle.exports

automatically created contexts defaults 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)   一些其他不解析的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.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

resolve.alias

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.  一个/abc/entry.js的调用的不同别名的设置

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. index.js可能会解析其他的文件,如果package.json设置了的话

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

包含你模块的目录(绝对路径),通常是一个目录数组,这个设置应该被用于添加个人目录到webpack查找路径里。

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.

resolve.fallback

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

webpack没有在resolve.root或者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". 解析模块的拓展名的数组。比如,为了发现一个CS文件,你这数组里应该包含字符串".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('./somefile.ext')),你需要在你的数组里添加一个空字符串。如果你希望模块加载不带拓展名(比如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"]

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.启用不安全的缓存来解析一部分文件。改变缓存路径也许会导致出错(罕见情况下)。 一个正则表达式数组里,只有一个正则或只有一个为true(对应全部文件)是最好的实践 。如果解析路径匹配,就会被缓存。

Default: []

resolveLoader

Like resolve but for loaders.  像是解析,但是是对于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"]
}

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. 注意,你可以用alias,其他特性和resolve相似。例如 {txt: 'raw-loader'}是 txt!templates/demo.txt 用 raw-loader后的结果

resolveLoader.moduleTemplates

That’s a resolveLoader only property. 这是resolveLoader 唯一的属性

It describes alternatives for the module name that are tried. 它描述了尝试的模块名称的替代名

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解析,但会成为bundle里的依赖。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.
  • 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 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.
  • array: Multiple values of the scheme (recursive).

字符串:一个精确匹配的依赖会变成外部依赖,同意的字符串会被用于外部依赖。

对象:如果依赖精确匹配到了对象的一个属性,属性值就会被当作依赖。属性值可以包含一个依赖型的前缀,用一个空格隔开。如果属性值为true,则使用该属性名。如果属性值为false,外部测试失败,这个依赖是内部依赖。见下面的例子。

函数:function(context, request, callback(err, result))。函数会在每个依赖中调用。如果结果被传递到回调函数里,这个值就会被像处理对象属性值那样处理。

正则表达式:每个被匹配的依赖都会成为外部依赖。匹配的文本会被用作外部依赖的请求。因为请求是用于生成外部代码钩子的确切代码,如果你匹配到一个cmd的包(比如 ‘../some/package.js’),相反使用外部function的策略。你可以通过callback(null, "require('" + request + "')"引入包,这个包生成module.exports = require('../some/package.js');使用要求在webpack上下文外。

数组:这个表的多个值(递归)

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的目标解析,将会执行amd或者umd的额外值

Note: If using umd you can specify an object as external value with property commonjscommonjs2amd and root to set different values for each import kind.  注意,如果用umd你可以指定一个对象的额外值,属性为 commonjscommonjs2amd和root会被设置不同的值

target

  • "web" Compile for usage in a browser-like environment (default) 在浏览器中使用的编译环境(默认值)
  • "webworker" Compile as WebWorker   被作为webworker编译
  • "node" Compile for usage in a node.js-like environment (use require to load chunks)   在nodejs环境下编译(用require加载chunks)
  • "async-node" Compile for usage in a node.js-like environment (use fs and vm to load chunks async)    在nodejs环境下编译(用fs和vm异步加载chunks)
  • "node-webkit" Compile for usage in webkit, uses jsonp chunk loading but also supports builtin node.js modules plus require(“nw.gui”) (experimental)在webkit下使用jsonp加载chunk,也支持在node中加入require(“nw.gui”) (实验性质)
  • "electron" Compile for usage in Electron – supports require-ing Electron-specific modules.

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.

提示,用analyze tool让它可视化,json 或者 stats.toJson()会给你JSON的统计。

cache

Cache generated modules and chunks to improve performance for multiple incremental builds.缓存生成模块和和chunks会增加新建多个工程的性能

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把传递的对象作为缓存。用这个方式,你可以在多个编译器调用的时候公用缓存。注意:不用在不同的配置调用的时候公用缓存。

watch

Enter watch mode, which rebuilds on file change.  进入查看模式,当文件变化的时候重建它。

watchOptions.aggregateTimeout

(only used when using CLI or simple node.js API)  只能用在CLI或者简单的node API上。

Delay the rebuilt after the first change. Value is a time in ms.  延迟第一次改变时的重建,值就是多长时间的毫秒数。

Default: 300

watchOptions.poll

(only used when using CLI or simple node.js API)

true: use polling    使用轮询

number: use polling with specified interval   在指定区间轮询

Default: undefined

debug

Switch loaders to debug mode.  选择loaders的debug模式

devtool

Choose a developer tool to enhance debugging.   选一个开发工具来加快调试

eval - Each module is executed with eval and //@ sourceURL.    每个模块都用eval执行

source-map - A SourceMap is emitted. See also output.sourceMapFilename.  触发SourceMap,详情看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.    SourceMap被作为dataurl加入到js文件中

eval-source-map - Each module is executed with eval and a SourceMap is added as DataUrl to the eval. 每个模块都用eval执行,并且SourceMap被作为dataurl加入到eval中

cheap-source-map - A SourceMap without column-mappings. SourceMaps from loaders are not used.如果sourcemap没有映射,loaders的sourcemao就不会启用。

cheap-module-source-map - A SourceMap without column-mappings. SourceMaps from loaders are simplified to a single mapping per line.    sourcemap没有映射,sourcemap就简单的映射到每一行。

Prefixing @# or #@ will enforce a pragma style. (Defaults to #, recommended)   前缀@,#或# @将加强语用风格。(默认为#,推荐)

Combinations are possible. hiddeninlineeval and pragma style are exclusive.  也可以组合使用,hiddeninlineeval和语意风格都是单独的。

i. e. cheap-module-inline-source-mapcheap-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-eval-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.

Example:  当webpack的配置已经传入了webpack-dev-server CLI,就可配置webpack-dev-server的行为

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

node

Include polyfills or mocks for various node stuff    对于不同节点包含polufills或者mocks

  • consoletrue or false 
  • globaltrue or false
  • processtrue"mock" or false
  • Buffertrue or false
  • __filenametrue (real filename), "mock" ("/index.js") or false
  • __dirnametrue (real dirname), "mock" ("/") or false
  • <node buildin>true"mock""empty" or 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.amd和 define.amd的值

Example:amd: {jQuery: true}  (for old 1.x AMD versions of jquery)

loader

Custom values available in the loader context.  在loader上下文中可用自定义值

recordsPathrecordsInputPathrecordsOutputPath

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

An absolute path is expected. recordsPath is used for recordsInputPath and recordsOutputPath if they left undefined.期望是绝对路径,recordsPath 被用于recordsInputPath 和recordsOutputPath,如果他俩未定义。

This is required, when using Hot Code Replacement between multiple calls to the compiler.当使用热替换之间的多个调用编译器的时候,这个选项是必须的。

plugins

Add additional plugins to the compiler.向编译器添加额外的插件。

上一篇:Falcon:三代reads比对组装工具箱


下一篇:关于open falcon 与nightingale 的一些调研