hash,chunkhash,contenthash的区别? hash:根据总资源列表生成的hash chunkhash:根据每一个chunk资源生成的hash contenthash:根据具体的文件生成的hash
index.js:
var src = require("./assets/webpack.png")
console.log(src);
var img = document.createElement("img")
img.src = src;
document.body.appendChild(img);
webpack.config.js:
module.exports = {
mode: "development",
devtool: "source-map",
module: {
rules: [
{
test: /\.(png)|(jpg)|(gif)$/,
use: [{
loader: "./loaders/img-loader.js",
options: {
limit: 3000, //3000字节以上使用图片,3000字节以内使用base64
filename: "img-[contenthash:5].[ext]"
}
}]
}
]
}
}
img-loader.js:
var loaderUtil = require("loader-utils")
function loader(buffer) { //给的是buffer,也就是二进制格式
console.log("文件数据大小:(字节)", buffer.byteLength);
var { limit = 1000, filename = "[contenthash].[ext]" } = loaderUtil.getOptions(this); //此处是解构语法。 也可以var options = loaderUtil.getOptions(this);
if (buffer.byteLength >= limit) { //超过限度,生成图片文件
var content = getFilePath.call(this, buffer, filename);
}
else{
var content = getBase64(buffer)
}
return `module.exports = \`${content}\``;
}
loader.raw = true; //该loader要处理的是原始数据
module.exports = loader;
function getBase64(buffer) {
return "data:image/png;base64," + buffer.toString("base64"); //图片字符串格式
}
function getFilePath(buffer, name) {
var filename = loaderUtil.interpolateName(this, name, { //生成一个名字。name也可以是"[contenthash]".[ext] ext:自动生成后缀
content: buffer //文件内容
});
this.emitFile(filename, buffer); //emitFile:往hash里加入资源
return filename;
}
效果: