Commit f9185442 by hank

inlineSourcePlugin

parent a292c71a
const HtmlWebpackPlugin = require('html-webpack-plugin');
class InlineSourcePlugin {
constructor(match) {
this.reg = match
}
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
}
apply(compiler) {
// 要通过html-webpack-plugin
compiler.hooks.compilation.tap('InlineSourcePlugin', (compilation) => {
console.log('The compiler is starting a new compilation...')
// Staic Plugin interface |compilation |HOOK NAME | register listener
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'alterAssetPlugin', // <-- Set a meaningful name here for stacktraces
(data, cb) => {
// Manipulate the content
data = this.processTags(data, compilation)
// Tell webpack to move on
cb(null, data)
}
)
})
}
}
/**
* new InlineSourcePlugin({
* match: /\.(js|css)/
* })
*
*/
module.exports = InlineSourcePlugin
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment