HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template.

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

This setup generates 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>

Although this setup works well when accessing the application from the root URL (localhost:3000/), it encounters issues when accessed from other URLs like localhost:3000/items/1. This is because the relative paths of the injected files cause them to be searched for within non-existent directories.

To resolve this issue, I need to modify the configuration so that the files are injected with absolute paths. Alternatively, I may adjust my express server to handle the routing differently.

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

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

In essence, I need to ensure that the script tag:

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

includes a slash at the beginning of the source path:

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

Answer №1

One way to solve this issue is by adjusting the publicPath in your webpack configuration:

output.publicPath = '/'

The HtmlWebpackPlugin relies on the publicPath to correctly prepend the URLs of the injected files.

Alternatively, you can also specify the base href within the <head> section of your HTML template to define the base URL for all relative links in your document.

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

Answer №2

After some troubleshooting, I found that I needed to add the following:

output.publicPath: './';

This was necessary in order for the application to function correctly when not installed at the root path. At the same time, I also included:

baseUrl: './'

injected into

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

By setting both parameters, the issue was resolved seamlessly.

Answer №3

For your webpack configuration:

config.output.publicPath = ''

In the index.html file:

<base href="/specificurl/" />

Implementing these changes should resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...

Data loss from AngularJS multipartForm directive when redirecting to different routes

Having trouble with an Excel file uploader and data parsing in the routes? It seems like the FormData is getting lost when sent through the $http service route. Any advice or experience on how to handle this issue would be greatly appreciated! Html View: ...

Tips for parsing JSON using JavaScript

I am looking to iterate through a JSON object that looks like {"key1":"val1","key2":"val2","key3":"val3"} in a loop. Here is my attempt: var inobj = '[{"key1":"val1","key2":"val2","key3":"val3"}]'; var obj = eval(inobj); for (var i = 0; i ...

Does ng-include fetch the included HTML files individually or merge them into a single HTML file before serving?

Is there a performance impact when using the ng-include Angular directive, in terms of having included HTML files downloaded as separate entities to the user's browsers? I am utilizing a CDN like AWS CloudFront instead of a node server to serve the H ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

A Guide on Accessing Promise Results in AngularJS

In my code, I am using a controller to retrieve information from SharePoint. While debugging, I noticed that the value of data.d.UserProfileProperties.results[115].Value is what I need to display in the view. However, I am struggling to extract that value ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

"Troubleshooting async/await issue with Node.js Sequelize and configuring the connection

function credential(secretFromVault) { const creddetails = new ClientSecretCredential(clientId, tenantId, clientSecret); // Build the URL to reach your key vault const url = `https://<vaultName>.vault.azure.net/`; // Lastly, create our secre ...

Is there a tool that can help pinpoint the original collection for shared elements across multiple collections?

When given multiple collections/arrays, I am interested in identifying the common elements and which collections they belong to. This request is somewhat similar to this query, but there may be matching elements between collection1 and collection3, or eve ...

Bizarre Object notation with JavaScript

While browsing through a Library called WebApp.net, I stumbled upon this interesting piece of code: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 } ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

Having trouble with errors when trying to implement react-router-v6 with typescript

Having trouble with my code and receiving the following error: "Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | ...

The value in the textarea will stay unchanged even after the form has been submitted

I recently resolved my previous issue, but now I am seeking advice on how to prevent a textarea from clearing its input after submitting a form. You can view the jsFiddle here: http://jsfiddle.net/rz4pnumy/ Should I modify the HTML form? <form id="for ...

A step-by-step guide to displaying API data in a React frontend using functional components

I've managed to create a backend API using Node+Express+MSSQL and tested the routes with POSTMAN. However, I'm facing challenges when trying to display the data on the front-end using React Functional components/hooks. I'm unsure if I'm ...

props remain undefined even after being assigned in the redux store

I encountered an unusual error related to a reducer called prs when adding or deleting a person in an app. Essentially, this app allows users to add or remove a person with a unique ID assigned to each individual. To start off, here is the parent componen ...

Encountering an issue while trying to export a module in Node.js

I've been exploring the various ways to export modules in Node.js and have encountered an issue that I'm trying to wrap my head around. When exporting a module in Node.js, the following code works without any problems: const jwt = require(' ...

Creating a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Utilizing an SSL certification (pem file) within JavaScript

Currently in the process of developing a program to extract data from the FAA's AIDAP database. I received a security certificate in the form of a .p12 file, which I have successfully converted into a .pem file. However, I am encountering difficulties ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...