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.向編譯器添加額外的插件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM