Axel
Axel

Reputation: 5131

How to load script tag after the script injected by webpack?

Webpack automatically inserts transformable.js at the end of body tag. I want to have a script after the <script src="transformable.js"></script>. How can I achieve this?

This is my structure:

enter image description here

I want to have this i.e. load transformable.js first and then have script tag:

enter image description here

This is my webpack config:

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"
}

Upvotes: 3

Views: 4947

Answers (1)

felixmosh
felixmosh

Reputation: 35573

HTMLWebpackPlugin is the one that injects script & style tags, you can disable this behavior, and use the built-in tags to position the tags as you want.

<!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
    })
  ]
};

For a working example: https://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-insertion-position/webpack.config.js

Upvotes: 1

Related Questions