首页 > Windows开发 > 详细

webpack入门(四)webpack的api 2 module

时间:2016-01-30 13:33:42      阅读:875      评论:0      收藏:0      [点我收藏+]

接着介绍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.

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.

/abc/node_modules may resolve in /node_modules too.

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.

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.

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.

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

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.

resolve.packageMains

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

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

Not set by default

Example: "browser" to check the browser field.

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.

Default: []

resolveLoader

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

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

resolveLoader.moduleTemplates

That’s a resolveLoader only property.

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.

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 viacallback(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).

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"))
    ]
}
typevalueresulting 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 umd you can specify an object as external value with property commonjscommonjs2amd and root to set different values for each import kind.

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 builtin node.js modules plus require(“nw.gui”) (experimental)
  • "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.

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.

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.

watch

Enter watch mode, which rebuilds on file change.

watchOptions.aggregateTimeout

(only used when using CLI or simple node.js 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.

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.

Prefixing @# or #@ will enforce a pragma style. (Defaults to #, recommended)

Combinations are possible. hiddeninlineeval and pragma style are exclusive.

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.

devtoolbuild speedrebuild speedproduction supportedquality
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

devServer

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

Example:

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

node

Include polyfills or mocks for various node stuff:

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

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

loader

Custom values available in the loader context.

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.

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

plugins

Add additional plugins to the compiler.

webpack入门(四)webpack的api 2 module

原文:http://www.cnblogs.com/dh-dh/p/5168559.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!