Search code examples
urlwebpackbundlehtml-webpack-plugin

HtmlWebpakPlugin generating bundled asset url with leading double slash


Somehow HtmlWebpack plugin is generating an url with leading double slashes

<script defer src="//js/app.6f290bd2820c4c9e.bundle.js"></script>

That make the resource not being downloaded from the browser

enter image description here

Here is my webpack configuration

plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, './resources/html/index.html'),
        filename: 'index.html',
        inject: 'body',
    }),
],
output: {
    path: path.resolve(__dirname, 'public'),
    filename: '[name].[contenthash].bundle.js',
    clean: true,
}

I just need to have the url being generated with a single leading slash to work properly, better if without setting any base url so the code still work for both staging and production compilation.


Solution

  • You need to set publicPath in order to override the default settings that add a / to any not empty string.

     output: {
        path: path.resolve(__dirname, 'public'),
        filename: '[name].[contenthash].bundle.js',
        clean: true,
        publicPath: ''
    }
    

    with this configuration the output will be:

    <script defer src="/js/app.6f290bd2820c4c9e.bundle.js"></script>

    with a single / in the url.
    This is because of that:

    let publicPath = typeof compilation.options.output.publicPath !== 'undefined' 
       // If a hard coded public path exists use it 
       ? compilation.mainTemplate.getPublicPath({hash: compilationHash}) 
       // If no public path was set get a relative url path 
       : path.relative(path.resolve(compilation.options.output.path, path.dirname(self.childCompilationOutputName)), compilation.options.output.path) 
         .split(path.sep).join('/'); 
      
     if (publicPath.length && publicPath.substr(-1, 1) !== '/') { 
       publicPath += '/'; 
     } 
    

    Ref: https://github.com/jantimon/html-webpack-plugin/blob/8440e4e3af94ae5dced4901a13001c0628b9af87/index.js#L411-L420