文件列表插件
/*
最终结果
## 文件名 资源大小
- bundle.js 32157
- bundle.js.map 30826
- index.html 317
*/
class FileListPlugin{
constructor({filename}) {
this.filename = filename;
}
apply(compiler) {
compiler.hooks.emit.tap("FileListPlugin", (compilation, cb) => {
// 所有的资源都挂在compilation.assets属性上, 可以在属性上再加一个文件 这样就会被打包生成出来
let assets = compilation.assets;
let content = `## 文件名 资源大小\r\n`;
Object.entries(assets).forEach(element => {
let [filename, statObj] = element;
content += `- ${filename} ${statObj.size()}\r\n`
})
assets[this.filename] = {
source(){
return content;
},
size() {
return content.length;
}
}
})
}
}
module.exports = FileListPlugin;
复制代码
内联webpack插件
// 将外链标签变成内联
const HtmlWebpackPlugin = require("html-webpack-plugin");
class InlineSourcePlugin{
constructor({match}) {
this.reg = match; // 正则
}
apply(compiler) {
// 要通过htmlwebpackplugin实现这个功能
compiler.hooks.compilation.tap("InlineSourcePlugin", (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync("alterPlugin", (data,cb) => {
data = this.processTags(data, compilation); // 因为资源内容都放在compilation.assets上
cb(null,data);
})
})
}
processTags(data, compilation) { // 处理引入标签的数据
let headTags = [];
let bodyTags = [];
data.headTags.forEach(headTag => {
headTags.push(this.processTag(headTag, compilation))
})
data.bodyTags.forEach(bodyTag => {
bodyTags.push(this.processTag(bodyTag, compilation))
})
return {...data, headTags, bodyTags};
}
processTag(tag, compilation) { // 处理某一个标签
let newTag, url;
if(tag.tagName === "link" && this.reg.test(tag.attributes.href)){
newTag = {
tagName: "style",
attributes:{type:"text/css"}
};
url = tag.attributes.href;
}
if(tag.tagName === "script" && this.reg.test(tag.attributes.src)){
newTag = {
tagName: "script",
attributes:{type:"application/javascript"}
}
url = tag.attributes.src;
}
if(url) {
newTag.innerHTML = compilation.assets[url].source(); // 文件的内容 放到innerHTML属性上
delete compilation.assets[url]; // 删除掉原资源 否则还是会被单独打包生成文件
return newTag;
}
return tag;
}
}
module.exports = InlineSourcePlugin;
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END