jantimon/html-webpack-plugin

templateContent function did not get headTags added in afterTemplateExecution

clChenLiang opened this issue · 1 comments

Current behaviour 💣

I wound to set a templateContent as function. and inject with false. The templateContent function will use headTags, bodyTags to reorganize the html. And return a string html finally.
And there has an another plugin AutoSetRootFontSizePlugin will set headTags to HtmlWebpackPlugin.

Expected behaviour ☀️

In templateContent function, the headTags will include the script added by AutoSetRootFontSizePlugin.

Reproduction Example 👾

file index

image

webpack config

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

class AutoSetRootFontSizePlugin {
    constructor(options) {
        this.name = 'AutoSetRootFontSizePlugin';
    }
    apply(compiler) {
        compiler.hooks.compilation.tap(this.name, compilation => {
            HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(this.name, async (data) => {
                    data.headTags.unshift({
                        tagName: 'script',
                        attributes: {
                            type: 'text/javascript',
                        },
                        voidTag: false,
                        meta: {},
                        innerHTML: 'console.log(abc)',
                    });
                console.log('===> after unshift: ', data.headTags)

                return data;
            });
        });
    }
}

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
        templateContent: ({ htmlWebpackPlugin }) => {
           // In here, should include script added by AutoSetRootFontSizePlugin, but not
            console.log('===> htmlWebpackPlugin: ', htmlWebpackPlugin.tags.headTags);
            return '<!DOCTYPE html><head id="ab"></head>';
        },
        inject: false, // must to be false, in case templateContent returned string be added scripts twice
    }),
    new AutoSetRootFontSizePlugin()
  ]
}
{
    "scripts": {
        "build": "webpack "
    },
    "devDependencies": {
        "html-webpack-plugin": "^5.5.3",
        "webpack": "^5.88.2",
        "webpack-cli": "^5.1.4"
    }
}

Environment 🖥

npm install
npx webpack --config webpack.config.js

Use another hook to fixed this problem