【问题标题】:HTML Webpack Plugin <script> tag generated twiceHTML Webpack Plugin <script> 标签生成两次
【发布时间】:2021-10-01 02:31:28
【问题描述】:

如果我运行yarn run build,那么 HTMLWebpackPlugin 将从模板文件生成 index.html,但我的所有代码都会运行两次,因为脚本标签被添加了两次。

我的 index.html 模板文件:

<!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>

我从 HTMLWebpackPlugin 生成的 index.html:

<!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>

还有我的 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']
                    }
                }
            }
        ]
    }
};

所以,我的目标是在正文末尾添加一个脚本标签。

非常感谢您的帮助。

【问题讨论】:

    标签: javascript html webpack html-webpack-plugin


    【解决方案1】:

    如果向 HTML 添加标签,则必须禁用自动注入,并且在这种情况下注入必须为 false 而不是“body”。

    请检查文档 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

    【讨论】: