原文地址:https://webpack.js.org/loaders/file-loader/
webpack版本:2.2.1
特例:在組件的模板文件中,若以相對路徑的方式引用資源,file-loader在打包資源時不會改變圖片資源的路徑烹棉。建議在組件的模板文件中使用絕對路徑的方式引用資源洗做。若堅持使用相對路徑的方式驻呐,那么要使用如下形式:
src="${ require(' 資源的相對路徑') }"
Install
cnpm install --save-dev file-loader
Usage
默認情況下,經(jīng)file-loader處理后的文件的文件名變成了文件內(nèi)容的MD5 hash疏魏,后綴名為源文件的后綴名蛉艾。
var url = require("file-loader!./file.png");
// => emits file.png as file in the output directory and returns the public url
// =>returns i. e. "/public-path/0dcbbaa701328a3c262cfd45869e351f.png"
// 注:將file.png以一個文件的方式發(fā)布到輸出目錄下钳踊,并且在文件引用位置返回public url,此時文件引用是有效的勿侯,圖片能夠呈現(xiàn)出來拓瞪。
默認情況下,經(jīng)file-loader處理后的文件會被發(fā)布到輸出目錄下罐监,但如果需要的話也可以不發(fā)布(例如吴藻,對于服務(wù)端的包來說)
var url = require("file-loader?emitFile=false!./file.png");
// => returns the public url but does NOT emit a file
// => returns i. e. "/public-path/0dcbbaa701328a3c262cfd45869e351f.png"
//注: file-loader為文件引用位置返回了public url瞒爬,但是經(jīng)其處理后的文件沒有被發(fā)布到輸出目錄下弓柱,此時文件引用是無效的,圖片不能呈現(xiàn)出來侧但。
Filename templates
你可以使用查詢參數(shù)(query parameter)name
來為你的文件配置custom filename template(客戶端文件名模式 )矢空。例如,從context
目錄中復(fù)制一個文件到輸出目錄禀横,并且保留完整的目錄結(jié)構(gòu)屁药,你可以使用:
?name=[path][name].[ext]
默認情況下,你指定的path和name會將打包后的文件輸出到相同的目錄中柏锄,并且也會使用相同的 URL path來訪問該文件酿箭。
注意:在webpack2的配置文件中复亏,需將query parameter作為
options
的屬性進行設(shè)置。
你可以使用查詢參數(shù)outputPath
和publicPath
來指定custom output(客戶端輸出)和public paths:
use: "file-loader?name=[name].[ext]&publicPath=assets/foo/&outputPath=app/images/"
Filename template placeholders
-
[ext]
the extension of the resource -
[name]
the basename of the resource -
[path]
the path of the resource relative to the context query parameter or option. -
[hash]
the hash of the content, hex-encoded md5 by default -
[<hashType>:hash:<digestType>:<length>]
optionally you can configure - other
hashTypes
, i. e.sha1, md5, sha256, sha512
- other
digestTypes
, i. e.hex, base26, base32, base36, base49, base52, base58, base62, base64
- and
length
the length in chars -
[N]
the N-th match obtained from matching the current file name against the query param regExp
Examples
require("file-loader?name=js/[hash].script.[ext]!./javascript.js");
// => js/0dcbbaa701328a3c262cfd45869e351f.script.js
require("file-loader?name=html-[hash:6].html!./page.html");
// => html-109fa8.html
require("file-loader?name=[hash]!./flash.txt");
// => c31e9820c001c9c4a86bce33ce43b679
require("file-loader?name=[sha512:hash:base64:7].[ext]!./image.png");
// => gdyb21L.png
// use sha512 hash instead of md5 and with only 7 chars of base64
require("file-loader?name=img-[sha512:hash:base64:7].[ext]!./image.jpg");
// => img-VqzT5ZC.jpg
// use custom name, sha512 hash instead of md5 and with only 7 chars of base64
require("file-loader?name=picture.png!./myself.png");
// => picture.png
require("file-loader?name=[path][name].[ext]?[hash]!./dir/file.png")
// => dir/file.png?e43b20c069c4a01867c31e98cbce33c9