Search code examples
webpackhtml-webpack-plugin

How can I override the src tags generated by HtmlWebpackPlugin?


I have multiple outputs with some hash in the name in my Webpack configuration and that is why I try to utilize HtmlWebpackPlugin to auto-generate the index HTML file which serves the SPA app. So far so good.

However, because I serve the SPA app from an MVC framework with a template engine; I want it to decide where the assets are located. That means, I have to modify the <script> tags put by the HtmlWebpackPlugin like:

From:

<script type="text/javascript" src="public/js/app.js">

To:

<script type="text/javascript" src="{{asset('app.js')}}">

I read the docs and had an eye on the listed extensions but no luck. Is there any undocumented way of achieving what I am trying to do?


Solution

  • I developed a plugin to achieve that. Here is the source code:

    function HtmlWebpackLaravelAssetPlugin(options) {}
    
    HtmlWebpackLaravelAssetPlugin.prototype.apply = function (compiler) {
        compiler.plugin('compilation', (compilation) => {
    
            compilation.plugin(
                'html-webpack-plugin-after-html-processing',
                data => {
                    data.html = data.html.replace(/(src\=\"public\/)(.*?)(\"\>)/gi, 'src={{ asset("$2") }}>')
                }
            )
    
        })
    }
    
    module.exports = HtmlWebpackLaravelAssetPlugin