HTML Webpack Plugin <script> 标签生成两次

问题描述

如果我运行 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']
                    }
                }
            }
        ]
    }
};

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

非常感谢您的帮助。

解决方法

如果你在 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