specialgirlgotoheaven / MyBlog

MyBlog
0 stars 0 forks source link

webpack插件--inlineSourcePlugin.js #143

Open specialgirlgotoheaven opened 5 years ago

specialgirlgotoheaven commented 5 years ago

const HtmlWebpackPlugin = require('html-webpack-plugin')//要通过webpackPlugin(html-webpack-plugin)来实现这个功能 class InlineSourcePlugin { constructor(){ this.reg = this.match } apply(comilper){ //要通过webpackPlugin(html-webpack-plugin)来实现这个功能 comilper.hooks.compilation.tap('InlineSourcePlugin',(compilation)=>{ //拿出内置的插件 HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync('alterPlugin',(data,cb)=>{ console.log(data) 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(bodyTags =>{ bodyTags.push(this.processTag(bodyTags,compilation)) }) // return {...data,headTags,bodyTags} 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 === 'js' && 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; // plugins:[ // new InlineSourcePlugin({ // match:/.(js|css)/ // }) // ]