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按下列顺序执行。
- preloadersspecified in the configuration
- loadersspecified in the configuration
- loaders specified in the request (e.g. require('raw!./file.js'))
- postLoadersspecified 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.
webpack入门(七) API in LOADERS的更多相关文章
- webpack入门和实战(一):webpack配置及技巧
		一.全面理解webpack 1.什么是 webpack? webpack是近期最火的一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX).coffee.样式(含less/sass).图片等都 ... 
- webpack入门指南-step03
		一.webpack 的使用 webpack简单点来说就就是一个配置文件,所有的魔力都是在这一个文件中发生的. 这个配置文件主要分为三大块 entry 入口文件 让webpack用哪个文件作为项目的入口 ... 
- webpack入门(1)
		webpack入门(1) 源码戳这里 ps:每个案例对应相应的demo,例如"案例1"对应"demo1" 一.webpack基本功能及简单案例 安装webpac ... 
- webpack入门(四)——webpack loader 和plugin
		什么是loader loaders是你用在app源码上的转换元件.他们是用node.js运行的,把源文件作为参数,返回新的资源的函数. 例如,你可以用loaders告诉webpack加载 coffee ... 
- webpack入门指南(基于webpack v4.41.2)
		2019年12月5日初稿,目前webpack已经更新到v4.41.2,本文正是基于该版本,在windows8.1操作系统下进行的demo编译,适用于想入门webpack的前端开发人员. webpack ... 
- webpack入门教程之Hello webpack(一)
		webpack入门教程系列为官网Tutorials的个人译文,旨在给予想要学习webpack的小伙伴一个另外的途径.如有不当之处,请大家指出. 看完入门教程系列后,你将会学习到如下内容: 1.如何安装 ... 
- webpack入门——webpack的安装与使用
		一.简介 1.什么是webpack webpack是近期最火的一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX).coffee.样式(含less/sass).图片等都作为模块来使用和处理. ... 
- 一小时包教会 —— webpack 入门指南
		什么是 webpack? webpack是近期最火的一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX).coffee.样式(含less/sass).图片等都作为模块来使用和处理. 我们可以 ... 
- Webpack 入门指南 - 3. Hello, Angular2!
		Webpack 入门指南 - 1.安装 Webpack 入门指南 - 2.模块 这一次,我们使用 Webpack 来打包 Angular 2 的应用. 与官方的 Hello, Angular 2 项目 ... 
随机推荐
- JS 验证输入框输入  只允许输入正实数(正整数,正小数),其他情况下不能输入 oninput事件
			input标签的oninput事件 要求输入框只输入正实数,包括整数和小数. 具体要求:整数部分不超过7位,可以没有小数,若有位数不超过2位. <input type="text&qu ... 
- Linux的基本解读
			Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和UNIX的多用户.多任务.支持多线程和多CPU的操作系统 而严格来讲,Linux这个词本身只表示Linux内核,但实际上人 ... 
- Oracle 内存参数调优设置
			Oracle 数据库系统中起到调节作用的参数叫初始化参数,数据库管理员根据实际情况需要适当调整这些 初始化参数以优化Oracle系统. 1 主要系统参数调优介绍 2 系统内存参数的分配 2.1 Ora ... 
- WPF通过DynamicResource实现给界面动态更换皮肤
			在我们的程序中有时候需要去实现动态更换皮肤的效果,从而完成一些个性化的设置,那么我们究竟怎样去实现动态换皮肤的效果呢?那么我们经常用到的就是设置不同的Style,并且在主程序的xaml文件中通过Dyn ... 
- spring程序打包war,直接通过-jar启动,并指定spring.profiles.active参数控制多环境配置
			备注:spring boot有内嵌tomcat,jar项目可以用java -jar命令启动,war包也可以,且可以直接指定spring.profiles.active参数控制多环境配置 直接指定传参, ... 
- Java开发之@PostConstruct执行顺序
			构造函数==>postConstruct==>init==destory==>predestory==卸载servlet;; 从Java EE5规范开始,Servlet增加了两个影响 ... 
- Java Annotation详解 理解和使用Annotation
			系统中用到了java注解: 查了一下如何使用注解,到底注解是什么: (1)创建方法:MsgTrace Java Class==> 在Create New Class中: name:输入MsgTr ... 
- web攻擊
			一.dos攻擊 向服務器發送數量龐大的合法數據,讓服務器分不清是不是正常請求,導致服務器接收所有的請求.海量的數據請求會使得服務器停止服務和拒絕服務. 防禦:阿里云或其它資源服務器有專門web應用防火 ... 
- codeforces362B
			Petya and Staircases CodeForces - 362B 题意: 一个小男孩要上楼梯,他一次可以走1个台阶或2个台阶或3个台阶,但是有一些台阶是脏的,他不想走在脏台阶上.一共有n个 ... 
- POJ 2823 滑动窗口 单调队列
			https://vjudge.net/problem/POJ-2823 中文:https://loj.ac/problem/10175 题目 给一个长度为 $N$ 的数组,一个长为 $K$ 的滑动窗体 ... 
