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 项目 ...
随机推荐
- babel(一)
一.babel npm babel src/index.js -d lib 二.@babel/core @babel/cli @babel/core 转换语法核心 @babel/cli 执行 ...
- 四、Object.defineProperty总结
Object.defineProperty() 参考:https://segmentfault.com/a/1190000007434923 定义: 方法会直接在一个对象上定义一个新属性,或者修改一个 ...
- [转帖]震惊,用了这么多年的 CPU 利用率,其实是错的
震惊,用了这么多年的 CPU 利用率,其实是错的 2018年12月22日 08:43:09 Linuxer_ 阅读数:50 https://blog.csdn.net/juS3Ve/article/d ...
- [转帖]浅谈程序中的text段、data段和bss段
作者:百问科技链接:https://zhuanlan.zhihu.com/p/28659560来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 一般情况,一个程序本质上都 ...
- 在linux和本地系统之间进行数据传输的简单方法--lrzsz
lrzsz是一款在linux里可代替ftp上传和下载的程序. >>提君博客原创 http://www.cnblogs.com/tijun/ << 提君博客原创 安装和使用非 ...
- day 7-16 单表查询
一.准备工作 先把表建立好,方便一会查询. create table emp( id int not null unique auto_increment, name varchar(20) not ...
- C# Note33: 总结C# 6.0/7.0 新特性
先注明,本文主体参考自:C# 6.0新特性 目前代码中使用了很多C#6.0的新特性,下面以Point类来做相关叙述: public class Point { public int X { get; ...
- 解决Jupyter notebook[import tensorflow as tf]报错
参考: https://blog.csdn.net/caicai_zju/article/details/70245099
- hive JDBC客户端启动
JDBC客户端操作步骤
- git连接到github
基本流程如图 如何配置SSH key:在gitBash里执行. 1.检查电脑上是否生成过了,如果已经生成了,则需要删除后再操作 cd ~ cd .ssh 提示:No such file or dire ...