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>
output.publicPath = '/'
was the solution. – Langan