How to serve HtmlWebpackPlugin’s version of index.html on any route in development?

After reading this question, I understand that HtmlWebpackPlugin serves an in-memory version of index.html at http://localhost:8080/index.html and injects the bundles (in my case vendors.js and app.js) into the file.

I have an index.html template prepared in /src which is just this:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
</head>

<body>
<div id="app"></div>

<!-- htmlwebpackplugin scripts should inject below -->
</body>
</html>

When I visit the homepage at http://localhost:8080 I get this in the HTML inspector which is correct:

<!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
    </head>
    
    <body>
    <div id="app"></div>

    <!-- htmlwebpackplugin scripts should inject below -->
    <script src="/vendors.js"></script>
    <script src="/app.js"></script>
    </body>
    </html>

However if I visit another route directly in my app like http://localhost:8080/shop (which is served by Node/Express as server-side rendered) then I get the original version of index.html back without the bundled .js files at the bottom of the ` tag.

If HtmlWebpackPlugin’s index.html is only served at the root and in memory, then how can it be used as the template for Node/Express to send HTML to the browser? Node/Express is dealing with a route by looking at src/index.html and using that file on disk without the injected bundles created by HtmlWebpackPlugin.

The easy answer is to manually add vendor.js and app.js into src/index.html but messes up the production build as it contains references to these development files which don’t exist in production (they exist, but with hashed names).

What am I missing/doing wrong?

Source: Ask Javascript Questions

LEAVE A COMMENT