webpack入門(七) API in LOADERS

介紹css

loaders容許你用require() 預處理文件(preprocess files)或者加載他們,在其餘的構建工具中,loaders就是一種像「任務(tasks)」的東西。他提供了一種處理前端構建的強大的方式。loaders能夠從不一樣語言類型的文件來轉換文件,好比coffeescript,內聯image的data url。loaders甚至容許你在你的js文件中用require()加載css文件。html

讓webpack用loader轉換一個模塊,你能夠指定模塊須要的loader,就像在require()的調用。前端

var moduleWithOneLoader = require("my-loader!./my-awesome-module");

注意,!語法將loader從模塊路徑中分離開。loaders像模塊同樣能夠指定一個相對路徑,而不是它的loader名。node

require("./loaders/my-loader!./my-awesome-module");

loaders能夠被鏈式調用並用!分割開。這有利於在管道中轉換多個文件webpack

require("style-loader!css-loader!less-loader!./my-styles.less");

當使用鏈式調用的時候,loaders會被從右到左的應用。在上面的例子中,my-styles.less會首先被less-loader轉換爲css文件。而後被傳入到css-loader中處理url,字體和一些其餘資源。最後被傳入到style-loader中轉換成script標籤。git

參數github

loaders能夠接受查詢字符串。web

require("loader?with=parameter!./file");

查詢字符串的格式取決於loaders,因此去文檔裏查找該loaders接受的查詢字符串的格式。一般大部分loaders接受傳統的查詢字符串格式。express

loaders的配置api

每一個模塊具體的loaders均可以重複(brittle and repetitive),webpack提供了一個在webpack配置文件中指定那個loaders應用於不用同文件類型的方式。在大多數狀況下,推薦(recommended )在配置中指定,由於它不會在代碼中添加任何特定的語法,使其更可重用(reusable)。

{
    module: {
        loaders: [
            { test: /\.coffee$/, loader: "coffee-loader" }
        ],
        preLoaders: [
            { test: /\.coffee$/, loader: "coffee-hint-loader" }
        ]
    }
};

See the configuration page for more information about configuring loaders.  查看配置頁獲得關於配置loaders的更多信息。<-點擊

loader的順序

文件在文件系統中讀取後,loaders按下列順序執行。

  1. preloaders specified in the configuration 
  2. loaders specified in the configuration
  3. loaders specified in the request (e.g. require('raw!./file.js'))
  4. postLoaders specified in the configuration

您還能夠重寫模塊請求中的配置加載程序以適應特定的狀況。

  在一個請求中添加!!將禁用在配置中指定的全部loaders

    require("!raw!./script.coffee")

  在一個請求中添加!!將禁用在配置中指定的全部loaders

    require("!!raw!./script.coffee")

  在一個請求中添加-!將會禁用配置中的preLoaders和loaders可是不由用postLoaders

    require("-!raw!./script.coffee")

編寫loaders

寫一個loaders至關簡單,一個loader就是一個導出函數的一個文件。編譯器調用這個函數,傳入上一個的loader的結果或者源文件,這個函數的this上下文被編譯器填充了一些容許loader作的有用的方法,在其餘方面,改用異步調用方式和獲得查詢查詢字符串,第一個loader被傳入一個參數:源文件的內容。編譯器指望從最後一個loader獲得一個結果,結果應該爲一個字符串或者一個buffer(被字符串轉換而來),表明模塊的js源碼。SourceMap的結果(做爲JSON對象)可選的被傳入。一個單一的結果必須同步返回,多結果的回調函數(this.callback )必須被調用,異步模式下,this.async() 必須被調用,它返回this.callback。而後loader必須返回undefined並調用回調。

錯誤能夠被同步模式拋出或者調用它的回調函數傳入錯誤

webpack在任何狀況下都容許異步模式。

enhanced-require僅在require.ensure或者AMD加載的時候容許異步模式。

更詳細的說明和指南,check out How to write a loader.

例子

同步loader

module.exports = function(content) {
    return someSyncOperation(content);
};

異步loader

module.exports = function(content) {
    var callback = this.async();
    if(!callback) return someSyncOperation(content);
    someAsyncOperation(content, function(err, result) {
        if(err) return callback(err);
        callback(null, result);
    });
};

注意:建議給一個異步loader回落到同步模式的模式。不須要webpack但容許用enhanced-require運行同步的loader

raw loader

默認的源文件會做爲utf-8編碼的字符串被傳入到loader,設置raw爲true,loader就會做爲原Buffer被傳入。

每一個loader都容許把結果做爲字符串或者做爲Buffer,編譯器會在loader間轉換他們。

module.exports = function(content) {
    assert(content instanceof Buffer);
    return someSyncOperation(content);
    // return value can be a Buffer too
    // This is also allowed if loader is not "raw"
};
module.exports.raw = true;

pitching loader

這些loaders被從右到左被調用。但有些時候,這些loaders不關心這些結果是來自上一個loader仍是文件,他們只關心元數據(metadata);loader的 pitch方法會在loaders被調用以前被從左到右的調用,若是一個loader用pitch方法提供告終果,程序就會迴轉並跳過剩下的loaders,繼續調用更多的左邊的loaders。數據能夠在 pitch和普通調用間傳遞。

module.exports = function(content) {
    return someSyncOperation(content, this.data.value);
};
module.exports.pitch = function(remainingRequest, precedingRequest, data) {
    if(someCondition()) {
        // fast exit
        return "module.exports = require(" + JSON.stringify("-!" + remainingRequest) + ");";
    }
    data.value = 42;
};

 loader context

這些東西(stuff)在loader的this上是可用的。例如,這須要調用:

/abc/file.js:

require("./loader1?xyz!loader2!./resource?rrr");

 

版本

loader api的版本,當前1。

內容

字符串,模塊的目錄,能夠用做解決其餘問題的上下文。

在這個例子中:/abc由於resource.js 在目錄裏。(/abc because resource.js is in this directory)

request

The resolved request string.

In the example: "/abc/loader1.js?xyz!/abc/node_modules/loader2/index.js!/abc/resource.js?rrr"

query

A string. The query of the request for the current loader.

In the example: in loader1: "?xyz", in loader2: ""

data

A data object shared between the pitch and the normal phase.

cacheable

cacheable(flag = true: boolean)

 

Make this loader result cacheable. By default it’s not cacheable.

A cacheable loader must have a deterministic result, when inputs and dependencies haven’t changed. This means the loader shouldn’t have other dependencies than specified with this.addDependency. Most loaders are deterministic and cacheable.

loaders

loaders = [{request: string, path: string, query: string, module: function}]

 

An array of all the loaders. It is writeable in the pitch phase.

In the example:

[
  { request: "/abc/loader1.js?xyz",
    path: "/abc/loader1.js",
    query: "?xyz",
    module: [Function]
  },
  { request: "/abc/node_modules/loader2/index.js",
    path: "/abc/node_modules/loader2/index.js",
    query: "",
    module: [Function]
  }
]

 

loaderIndex

The index in the loaders array of the current loader.

In the example: in loader1: 0, in loader2: 1

resource

The resource part of the request, including query.

In the example: "/abc/resource.js?rrr"

resourcePath

The resource file.

In the example: "/abc/resource.js"

resourceQuery

The query of the resource.

In the example: "?rrr"

emitWarning

emitWarning(message: string)

 

Emit a warning.

emitError

emitError(message: string)

 

Emit an error.

exec

exec(code: string, filename: string)

 

Execute some code fragment like a module.

Hint: Don’t use require(this.resourcePath), use this function to make loaders chainable!

resolve

resolve(context: string, request: string, callback: function(err, result: string))

 

Resolve a request like a require expression.

resolveSync

resolveSync(context: string, request: string) -> string

 

Resolve a request like a require expression.

addDependency

addDependency(file: string)
dependency(file: string) // shortcut

 

Add a file as dependency of the loader result.

addContextDependency

addContextDependency(directory: string)

 

Add a directory as dependency of the loader result.

clearDependencies

clearDependencies()

 

Remove all dependencies of the loader result. Even initial dependencies and these of other loaders. Consider using pitch.

values (out)

Pass values to the next loaders inputValues. If you know what your result exports if executed as module, set this value here (as a only element array).

inputValues

Passed from the last loader. If you would execute the input argument as module, consider reading this variable for a shortcut (for performance).

options

The options passed to the Compiler.

debug

A boolean flag. It is set when in debug mode.

minimize

Should the result be minimized.

sourceMap

Should a SourceMap be generated.

target

Target of compilation. Passed from configuration options.

Example values: "web""node"

webpack

Set to true when this is compiled by webpack.

emitFile

emitFile(name: string, content: Buffer|String, sourceMap: {...})

 

Emit a file. This is webpack-specific

_compilation

Hacky access to the Compilation object of webpack.

_compiler

Hacky access to the Compiler object of webpack.

相關文章
相關標籤/搜索