webpack入门(七) API in LOADERS

介绍

loaders允许你用require() 预处理文件(preprocess files)或者加载他们,在其他的构建工具中,loaders就是一种像“任务(tasks)”的东西。他提供了一种处理前端构建的强大的方式。loaders可以从不同语言类型的文件来转换文件,比如coffeescript,内联image的data url。loaders甚至允许你在你的js文件中用require()加载css文件。

让webpack用loader转换一个模块,你可以指定模块需要的loader,就像在require()的调用。

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

注意,!语法将loader从模块路径中分离开。loaders像模块一样可以指定一个相对路径,而不是它的loader名。

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

loaders可以被链式调用并用!分割开。这有利于在管道中转换多个文件

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

当使用链式调用的时候,loaders会被从右到左的应用。在上面的例子中,my-styles.less会首先被less-loader转换为css文件。然后被传入到css-loader中处理url,字体和一些其他资源。最后被传入到style-loader中转换成script标签。

参数

loaders可以接受查询字符串。

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

查询字符串的格式取决于loaders,所以去文档里查找该loaders接受的查询字符串的格式。通常大部分loaders接受传统的查询字符串格式。

loaders的配置

每个模块具体的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.

原文地址:https://www.cnblogs.com/dh-dh/p/5179090.html