aherriot aherriot - 10 months ago 91
Javascript Question

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

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">
<link href="main-295c5189923694ec44ac.min.css" rel="stylesheet">
<div id="app"></div>
<script src="main-295c5189923694ec44ac.min.js"></script>

This works fine when visiting the root of the app
, but fails when I try to visit the app from another URL, for example,
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
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
directory and not at
? 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>

Answer Source

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 <title> of your html template, to specify the base url of all relative urls in your document.

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