【问题标题】:How to load script tag after the script injected by webpack?webpack注入脚本后如何加载脚本标签?
【发布时间】:2020-11-28 11:43:12
【问题描述】:

Webpack 会在 body 标签的末尾自动插入transformable.js。我想在<script src="transformable.js"></script> 之后有一个脚本。我怎样才能做到这一点?

这是我的结构:

我想要这个,即先加载transformable.js,然后有脚本标签:

这是我的 webpack 配置:

import path from "path"
import HtmlWebpackPlugin from "html-webpack-plugin"

export default {
    entry: "./src/index.ts",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "babel-loader"
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        })
    ],
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "transformable.js",
        sourceMapFilename: "[name].js.map"
    },
    devtool: "source-map"
}

【问题讨论】:

    标签: javascript typescript webpack


    【解决方案1】:

    HTMLWebpackPlugin 是注入脚本和样式标签的插件,您可以禁用此行为,并使用内置标签随意定位标签。

    <!DOCTYPE html>
    <html>
      <head>
        <%= htmlWebpackPlugin.tags.headTags %>
        <title>Custom insertion example</title>
      </head>
      <body>
        All scripts are placed here:
        <%= htmlWebpackPlugin.tags.bodyTags %>
        <script>console.log("Executed after all other scripts")</script>
      </body>
    </html>
    
    // webpack.config.js
    module.exports = {
      context: __dirname,
      entry: './example.js',
      output: {
        path: path.join(__dirname, 'dist/webpack-' + webpackMajorVersion),
        publicPath: '',
        filename: 'bundle.js'
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: 'index.html',
          inject: false, // <--- this disables the default injection
        })
      ]
    };
    

    对于一个工作示例:https://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-insertion-position/webpack.config.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2018-07-12
      • 1970-01-01
      相关资源
      最近更新 更多