Webpack assets run time dependency injection

less than 1 minute read

How to Inject Base Assets path URL dependency to webpack CSS bundle?

In your JavaScript project build by webpack, if you have requirement where at the build time you do not know the URL for the assets. And you want to put the assets base url at run time. For that webpack has global variable that can be set at run-time. Then below is the example for achieving that in webpack..

Create public-path.js file

This is the file which takes assetsBaseUrlfrom the window object. This variable will be passed at run time from the web application.

__webpack_public_path__ = window.assetsBaseUrl || '/';

Add public-path.js to bundle Index file

Create css.index.js and import public path in the css index

import './public-path';
import './css/mystyle.css';

Create a css bundle using css.index.js file only.

Define Desired Base Url in WebApp

In the HTML page you do something like this
In the Index.html file add below script tag where you set the required `assetsBaseUrl` before you add css.bundle.js script.

 var assetsBaseUrl = 'http://localhost:8002/dist/' 


Webpack has many global variables that can be set during run-time and those are very helpful for complex JavaScript web apps.