如何在webpack注入脚本后加载脚本标签?

3
Webpack会自动将transformable.js插入到标签的末尾。我想在<script src="transformable.js"></script>之后添加一个脚本。我该如何实现?
这是我的结构:

enter image description here

我希望先加载 transformable.js,然后再添加脚本标签:

enter image description here

这是我的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"
}
1个回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接