Webpack injection of output js into existing <script src="">

So as far as the regular behaviour goes, Webpack can inject it’s bundle into an HTML file, right?
With HtmlWebpackPlugin, selecting what gets injected can be done using the chunks.

plugins: [
  new HtmlWebpackPlugin({
    template: 'main.html',
    chunks: ['run']
  })
]

However, what about a case where I want to replace an existing html script tag with a compiled, hashed version of that same file, after all the CommonJS compiling and moduling Webpack does?

<body>
    <h1>My Webpack App is alive!</h1>
    <p>Run, my dear boi!</p>

    <script src="./script/run.ts"></script>
</body>

To become after compilation:

<body>
    <h1>My Webpack App is alive!</h1>
    <p>Run, my dear boi!</p>

    <script src="./script/run.js?62ea5d"></script>
</body>

This works BTW, if I use it for SCSS files , but not for bundle files.

I find this way more convenient to work with , especially since my team is used to referring to many JS files like this, plus thanks to being in the template I can add and remove scripts freely without restarting the Webpack process.

Source: Ask Javascript Questions

LEAVE A COMMENT