Macuroon 2015-10-09
加载器其实就是应用于你的程序的资源文件的转换器。它们将资源文件作为参数传入,然后返回新的资源。
例如,你可以使用加载器告诉webpack加载CoffeeScript文件或者JSX文件。
加载器都都是一些相似的模块。使用node.js兼容JavaScript的方式编写,并导出方法。通常情况下,你使用npm管理加载器,然而你也可以将加载器以文件的形式引入你的应用中。
如果加载器是发不到npm上的,你可以通过下面的方式安装:
$ npm install xxx-loader --save
或者
$ npm install xxx-loader --save-dev
这里有很多种方式使用加载器:
备注:如果你希望你的代码和环境无关,请尽量不要使用这种方式。而应该使用配置文件配置加载器。
可以使用require声明(或者define,require.ensure,等等)定义加载器。使用'!'分隔加载器,每一个部分都相对于当前文件夹解析。
例如:
require("./loader!./dir/file.txt");
// => uses the file "loader.js" in the current directory to transform
// "file.txt" in the folder "dir".
require("jade!./template.jade");
// => uses the "jade-loader" (that is installed from npm to "node_modules")
// to transform the file "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".你可以通过配置文件将加载器和正则绑定:
{
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"] },
]
}
}你可以通过命令行将加载器和指定扩展后缀绑定:
$ webpack --module-bind jade --module-bind 'css=style!css'
上面的命令设置使用“jade”加载器加载“.jade”文件,使用“style”和“css”加载器加载“.css”文件。
加载器可以通过查询字符串(就像web中一样)传递查询参数。查询字符串被添加在“?”后,例如:url-loader?mimetype=image/png
备注:查询字符串的格式取决于加载器本身。具体格式请参考对应的加载器文档。大多数加载器都使用通常的查询格式(?key=value&key2=value2)和JSON对象格式(?{"key":"value","key2":"value2"})
require("url-loader?mimetype=image/png!./file.png");{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }或者
{
test: /\.png$/,
loader: "url-loader",
query: { mimetype: "image/png" }
}webpack --module-bind "png=url-loader?mimetype=image/png"