Rspack provides the output.publicPath option, which sets the base URL path prefix for bundled static assets (such as JS, CSS, images, etc.).
Imagine the following scenarios:
In these scenarios, configuring output.publicPath
can help you load static assets correctly.
Set output.publicPath
to /
, then the assets path will be relative to the root path.
With this configuration, the assets access path is http://[domain]/
, for example http://localhost:8080/main.js
.
If your application needs to be deployed under a subdirectory, you can set output.publicPath
to the corresponding subdirectory path:
With this configuration, all assets will be loaded from the /assets/
path, for example http://localhost:8080/assets/main.js
.
output.publicPath
usually ends with /
.output.publicPath
to a relative path, such as ./assets/
. Using a relative path may cause assets to load incorrectly when they are located at different path depths.output.publicPath
to an empty string, the asset URL path will be relative to the HTML page (same directory).When deploying static assets using CDN, you can set output.publicPath
based on the environment variable, and set it to the CDN URL prefix during the production build.
With this configuration:
http://[domain]/
, for example http://localhost:8080/main.js
.https://cdn.example.com/
, for example https://cdn.example.com/main.[hash].js
.You can set publicPath
dynamically using __webpack_public_path__
in your JavaScript code.
The __webpack_public_path__
will override the output.publicPath
in the Rspack config, but it will only take effect for dynamically loaded assets, not for assets loaded via <script src="...">
.
First create a publicPath.js
:
Then import it into the first line of the entry file to ensure that publicPath
is set before async assets are loaded:
There are chances that you don't know what the publicPath
will be in advance, and Rspack can automatically calculate the publicPath
value by parsing some variables like import.meta.url, document.currentScript, script.src
or self.location
.
What you need is to set output.publicPath
to 'auto'
: