How can I push a new tag into "htmlWebpackPlugin.tags"
zhouzebin opened this issue · 2 comments
Prerequisites
- htmlWebpackPlugin@4.5.0
- react@17.0.2
Description
我想动态添加html的js资源,(除了打包产物以外的资源),
在htmlWebpackPlugin@3 中可以直接配置templateParameters为function,修改asstes.js和assete.css即可;
但在htmlWebpackPlugin@4.5.0 中templateParameters多了一个参数assetTags,修改并不管用.
I want to dynamically add HTML JS resources (other than those packaged),
You can configure TemplateParameters to function directly from htmlWebpackPlugin@3 by modifying asstes.js and asset. CSS.
However, htmlWebpackPlugin@4.5.0 has an additional parameter for templateParameters, assetTags, which doesn't help.
Config
module.exports = {
entry: '...',
output: {
...
},
module: {
rules: [
...
]
}
plugins: [
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
templateParameters(compilation, assets, assetTags, options) {
const url = '//s20.lgstatic.com/components/edu-fe/edu-userlogin-component/1.1.0/js/base-vendors.js'
// push assets in this step
assets.js.push(url)
assetTags.bodyTags.push({
tagName: 'script',
voidTag: false,
attributes: { src: url, defer: false },
toString: assetTags.bodyTags[0].toString
})
return {
compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options
},
'foo': 'bar'
};
}
},
)
),
...
]
}
It does not work , why?
Environment
Node.js v10.16.0
darwin 18.7.0
npm@6.9.0
webpack@4.44.2
html-webpack-plugin@4.5.0
Unfortunately you will need to write a small plugin - like this:
plugin.js
// If your plugin is direct dependent to the html webpack plugin:
const HtmlWebpackPlugin = require('html-webpack-plugin');
class MyPlugin {
apply (compiler) {
compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
// Static Plugin interface |compilation |HOOK NAME | register listener
HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapAsync(
'MyPlugin', // <-- Set a meaningful name here for stacktraces
(data, cb) => {
const {
html,
headTags,
bodyTags,
} = data;
// Modify headTags or bodyTags
/* ... */
// Tell webpack to move on
cb(null, data)
}
)
})
}
}
module.exports = MyPlugin
webpack.config.js
plugins: [
new MyPlugin()
]
This issue had no activity for at least half a year. It's subject to automatic issue closing if there is no activity in the next 15 days.