开发 在 vue 中使用的 htmlWebpackPlugin 插件
htmlWebpackPlugin 版本
在node_modules\_@vue_preload-webpack-plugin@1.1.1@@vue 文件夹下查看package.json, vue内置使用的 3.2.0 版本的插件
插件开发
在node_modules\_@vue_preload-webpack-plugin@1.1.1@@vue 文件夹下查看src/index.js, vue 使用的插件开发
class PreloadPlugin {
// ... 无关代码
apply (compiler) {
const skip = data => {
const htmlFilename = data.plugin.options.filename
const exclude = this.options.excludeHtmlNames
const include = this.options.includeHtmlNames
return (
(include && !(include.includes(htmlFilename))) ||
(exclude && exclude.includes(htmlFilename))
)
}
compiler.hooks.compilation.tap(
this.constructor.name,
compilation => {
compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tap(
this.constructor.name,
(htmlPluginData) => {
if (skip(htmlPluginData)) {
return
}
this.generateLinks(compilation, htmlPluginData)
}
)
compilation.hooks.htmlWebpackPluginAlterAssetTags.tap(
this.constructor.name,
(htmlPluginData) => {
if (skip(htmlPluginData)) {
return
}
if (this.resourceHints) {
htmlPluginData.head = [
...this.resourceHints,
...htmlPluginData.head
]
}
return htmlPluginData
}
)
}
)
}
}
}
module.exports = PreloadPlugin
插件开发的格式
class MyPlugin {
apply(compiler) {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tap(
"MyPlugin",
(htmlPluginData) => {
// 处理html => htmlPluginData.html
}
)
}
}
自己开发的插件
const pluginName = 'MyHtmlPlugin';
/**
* 在生产环境打包的时候,给 html 中插入 vue 相关的静态资源的地址
* 优化首屏加载速度、还要配置webpack打包的时候,不打包相关的资源
*/
class MyHtmlPlugin {
apply(compiler) {
compiler.hooks.compilation.tap(
pluginName,
compilation => {
compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tap(
pluginName,
(htmlPluginData) => {
htmlPluginData.html = htmlPluginData.html.replace(
`<!-- html plugin add script injected -->`,
`
<script src="/js/vue.min.js"></script>
<script src="/js/vuex.min.js"></script>
<script src="/js/vue-router.min.js"></script>
<script src="/js/axios.min.js"></script>
`
)
}
)
}
)
}
}
module.exports = MyHtmlPlugin;
插件使用
在vue.config.js中使用
// 导入MyHtmlPlugin
module.exports = {
// ... 无关代码
configureWebpack: {
// ... 无关代码
plugins: [
new MyHtmlPlugin()
]
}
}
注意:
htmlWebpackPluginBeforeHtmlProcessing 是 htmlwebpackPlugin 提供的事件
所有的事件
Sync
html-webpack-plugin-alter-chunks
Async
html-webpack-plugin-before-html-generation
html-webpack-plugin-before-html-processing
html-webpack-plugin-alter-asset-tags
html-webpack-plugin-after-html-processing
html-webpack-plugin-after-emit
现在的html-webpack-html 官方已经提供的 是 4.3.0
新版本的事件使用有了新的变动