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 configurationloadersspecified 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 项目 ...
随机推荐
- 配置router列表
import Vue from "vue"; import VueRouter from 'vue-router'; import Star from '../components ...
- nginx配置ssl证书后无法访问https
一直听说https更安全,要安装证书,一直没试过,今天终于试了试 首先得有个http的域名网站,服务器. 到阿里云的安全-ssl证书管理申请一个免费的,可以绑定一个域名 然后完善资料,照着例子配置一 ...
- Golang的channel使用以及并发同步技巧
在学习<The Go Programming Language>第八章并发单元的时候还是遭遇了不少问题,和值得总结思考和记录的地方. 做一个类似于unix du命令的工具.但是阉割了一些功 ...
- linux重装系统,如何保存硬盘中的内容
以前没有太关注重装系统如何保留下硬盘中的内容.但是最近有一些文件在重装系统后确实需要继续保留下来,于是花了点时间了解下磁盘分区相关的东东. 参考 http://blog.csdn.net/openn/ ...
- PHPCMS的使用
1.下载安装phpcms 下载完后解压将install_packages上传到服务器并重命名为phpcms_test: 更改目录文件系统权限: chmod -R 777 phpcms_test 配置n ...
- MySQL——基础操作
参考博客:http://www.cnblogs.com/wupeiqi/articles/5713315.html 1.创建用户.授权(默认root,密码为空) 创建: create user 'al ...
- WinForm中在非UI线程更改控件值的办法
从非UI线程调用UI控件赋值.或进行其他更新UI的操作的话,会出现异常: System.InvalidOperationException:“线程间操作无效: 从不是创建控件“xxx”的线程访问它.” ...
- SSH整合Maven教程
http://www.cnblogs.com/xdp-gacl/p/4239501.html
- Nginx 热部署最版本
L10 进入nginx里的sbin目录 拷贝原先的做备份 cp nginx nginx.old 然后将已经编译好的nginx二进制文件复制到sbin目录下并覆盖原有的二进制文件 kill -USR2 ...
- Linux系统下手把手完成无人值守安装服务
刚入职的运维新手经常会被要求去做一些安装操作系统的工作,如果按照用镜像光盘安装操作系统,效率会相当低下.那么如何提升效率,搭建出一套可以批量安装Linux系统的无人值守的安装系统? PXE+TFTP+ ...