什么是加載器
加載器本質上也是個 Javascript 模塊,他的功能是將各種資源轉換成易于使用的形式
加載器的特征
- 加載器可以鏈式調用,最后一個加載器必須返回 Javascript
- 加載器可以是同步的,也可以是異步的
- 加載器通過 Node.js 運行,因此可以做操作系統權限下的任何事情
- 加載器接收參數,英此時可配置的
- 加載器可以用正在表達式配置
- 加載器通過
npm
發布和安裝 - 不僅可以在配置文件中使用加載器,也可以在代碼中直接導入加載器模塊
- 其他特征
解析
加載器本質上就是個模塊,可以想模塊一樣使用它
命名約定
一般加載器的命名格式為 XXX-loader
,其中 XXX
表示要處理的資源類型,比如 json-loader
既可以用完整命名引用加載器 (比如 json-loader
),也可以用短名稱引用 (比如 json
)
安裝
通過 npm
安裝
$ npm install xxx-loader --save
或者
$ npm install xxx-loader --save-dev
使用方法
有三種方式來使用加載器
- 在代碼中通過
require
語句直接調用 - 通過配置文件使用
- 在命令行中使用
require
方式
- 使用感嘆號
!
將加載器和資源分隔開 - 路徑是相對于當前位置的相對路徑
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"
// If configuration has some transforms bound to the file, they will still be applied.
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.
配置文件方式
在配置文件中,可以使用正則表達式,讓加載器處理某種類型的所有文件
{
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 中的查詢字符串相同
require
形式
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"