Warm tip: This article is reproduced from serverfault.com, please click

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

(javascript - How to load script tag after the script injected by webpack?)

发布于 2020-11-28 11:43:12

Webpack会自动transformable.js在body标签的末尾插入我想在后面有个脚本<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"
}
Questioner
Damon
Viewed
11
felixmosh 2020-11-29 16:46:24

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