HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

JavascriptExpressWebpackReact Router

Javascript Problem Overview


I am using webpack and the HtmlWebpackPlugin to inject bundled js and css into an html template file.

new HtmlWebpackPlugin({
   template: 'client/index.tpl.html',
   inject: 'body',
   filename: 'index.html'
}),

And it produces the following html file.

<!doctype html>
<html lang="en">
  <head>
    ...
    <link href="main-295c5189923694ec44ac.min.css" rel="stylesheet">
  </head>
  <body>
    <div id="app"></div>
    <script src="main-295c5189923694ec44ac.min.js"></script>
  </body>
</html>

This works fine when visiting the root of the app localhost:3000/, but fails when I try to visit the app from another URL, for example, localhost:3000/items/1 because the bundled files are not injected with an absolute path. When the html file is loaded, it will look for the js file inside the non-exist /items directory because react-router hasn't loaded yet.

How can I get HtmlWebpackPlugin to inject the files with an absolute path, so express will look for them at the root of my /dist directory and not at /dist/items/main-...min.js? Or maybe I can change my express server to work around the issue?

app.use(express.static(__dirname + '/../dist'));

app.get('*', function response(req, res) {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

Essentially, I just need to get the line:

<script src="main...js"></script>

to have a slash at the start of the source.

<script src="/main...js></script>

Javascript Solutions


Solution 1 - Javascript

Try setting the publicPath in your webpack config:

output.publicPath = '/'

HtmlWebpackPlugin use the publicPath to prepend the urls of the injects.

Another option is to set the base href in the <head> of your html template, to specify the base url of all relative urls in your document.

<base href="http://localhost:3000/">

Solution 2 - Javascript

In fact, I had to put :

output.publicPath: './';

in order to have it working in a non-ROOT path. At the same time I was injecting :

   baseUrl: './'

into

<base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">

With both parameter set, it worked like a charm.

Solution 3 - Javascript

in webpack config

config.output.publicPath = ''

in your index.html

<base href="/someurl/" />

this should do it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaherriotView Question on Stackoverflow
Solution 1 - JavascriptMagnus SjungareView Answer on Stackoverflow
Solution 2 - JavascriptKevin FONTAINEView Answer on Stackoverflow
Solution 3 - Javascripthannad rehmanView Answer on Stackoverflow