Search code examples
javascripthtmlwebpackhtml-webpack-plugin

HTML Webpack Plugin <script> tag generated twice


If I run yarn run build then the HTMLWebpackPlugin will generate the index.html from a template file, but all my code runs twice because the script tag are added two times.

My index.html template file:

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><%= htmlWebpackPlugin.options.title %></title>
        <%= htmlWebpackPlugin.tags.headTags %>
    </head>
    <body>
        <div id="app"></div>
        <%= htmlWebpackPlugin.tags.bodyTags %>
    </body>
</html>

My index.html that is generated from HTMLWebpackPlugin:

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>My Website</title>
        
    </head>
    <body>
        <div id="app"></div>
        <script defer src="ecaecb1a919bc0a6e577.main.js"></script>
        <script defer src="ecaecb1a919bc0a6e577.main.js"></script>
    </body>
</html>

and my webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: '[fullhash].main.js',
        path: path.resolve(__dirname, 'dist'),
    },
    mode: "development",
    devServer: {
        contentBase: './dist',
        port: 9000,
        hot: true
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: "My Website",
            template: path.join(__dirname, "src/webpack_template.html"),
            inject: "body",
            hash: false
        }),
        new CleanWebpackPlugin()
    ],
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    }
};

So, my target is that one script tag will be at the end of the body.

Thank you very much for your help.


Solution

  • If you add tags to HTML, you must disable automatic injection and inject must be false in this case not "body".

    Please check documentation https://github.com/jantimon/html-webpack-plugin#options

    true || 'head' || 'body' || false Inject all assets into the given template or templateContent. When passing 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element. Passing true will add it to the head/body depending on the scriptLoading option. Passing false will disable automatic injections. - see the