loaders被应用于应用程序的资源文件中,通常用来做转换。它们都是函数(运行在nodejs中),将资源文件的源码作为入参,处理完后,返回新的源码文件。
例如,你可以使用loaders告诉webpack加载coffeescript和jsx。
npm
进行发布和安装。如果你对一些loaders的例子感兴趣,可以访问list of loaders。
loaders被解析为类似于模块的形式。一个loader模块被期望返回一个函数,并按照nodejs环境中的javascript规范编码。通常使用npm来管理这些loaders,但是你也可以在你的项目中通过文件的形式来使用这些loaders。
按照惯例,虽然不是必须的,loaders 通常被命名为XXX-loader,其中XXX是上下文名称,例如,JSON-loader。
你能通过loader的全名(实际的名称,如:json-loader),或者简写的形式(如:json)来引用它们。
loader的命名惯例和优先级搜索顺序都在webpack的配置API,resolveLoader.moduleTemplates中进行定义的。
loader的命名惯例还是比较有用的,尤其在require()表达式中引用它们,可以见下面的使用。
如果loader在npm中存在,那么我们可以通过如下命令来安装loader:
$ npm install xxx-loader --save
或者
$ npm install xxx-loader --save-dev
有很多种方式在你的项目中来使用loaders:
注意:如果非必须的话,或者你打算你的脚本运行于不可知的环境(nodejs和浏览器),否则尽量不要使用这种方式,而是使用配置约定来使用loaders(见下节)。
在require语句(define,require.ensure, etc…)指定加载哪些loaders是可能的。只是在资源中使用!来分割loaders。每个部分相对于当前目录进行解析。
在整个规则前加上!来覆盖配置中的loaders是完全可能的。
require("./loader!./dir/file.txt");
// => 在当前目录使用文件 "loader.js"来转换"dir"目录中的"file.txt"。
require("jade!./template.jade");
// => 使用"jade-loader" (that is installed from npm to "node_modules")
// => 转换文件 "template.jade"
// => 如果配置文件中对该文件有转换,它们仍然会被应用。
require("!style!css!less!bootstrap/less/bootstrap.less");
// => the file "bootstrap.less" in the folder "less" in the "bootstrap"
// module (that is installed from github to "node_modules") is
// transformed by the "less-loader". The result is transformed by the
// "css-loader" and then by the "style-loader".
// If configuration has some transforms bound to the file, they will not be applied.
你可以通过配置中的正则表达式来绑定loader:
{
module: {
loaders: [
{ test: /\.jade$/, loader: "jade" },
// => "jade" loader is used for ".jade" files
{ test: /\.css$/, loader: "style!css" },
// => "style" and "css" loader is used for ".css" files
// Alternative syntax:
{ test: /\.css$/, loaders: ["style", "css"] },
]
}
}
你可以通过CLI绑定loaders来进行扩展。
$ webpack --module-bind jade --module-bind 'css=style!css'
Loader能通过查询字符串(类似于web)来传递参数,查询字符串被添加在loader后面,中间用?连接。如:url-loader?mimetype=image/png
。
注意:查询字符串的格式是依赖于loader的。大部分的loader接收普通的查询字符串(?key=value&key2=value2
)和JSON对象(
?{“key”:”value”,”key2”:”value2”}`)。
require
require("url-loader?mimetype=image/png!./file.png");
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
webpack --module-bind "png=url-loader?mimetype=image/png"