ThepublicPath configuration option can be quite useful in a variety of scenarios. It allows you to specify the base path for all the assets within your application.
There are a few use cases in real applications where this feature becomes especially neat. Essentially, every file emitted to youroutput.path directory will be referenced from theoutput.publicPath location. This includes child chunks (created viacode splitting) and any other assets (e.g. images, fonts, etc.) that are a part of your dependency graph.
In development for example, we might have anassets/ folder that lives on the same level of our index page. This is fine, but what if we wanted to host all these static assets on a CDN in production?
To approach this problem you can easily use a good old environment variable. Let's say we have a variableASSET_PATH:
import webpackfrom'webpack';// Try the environment variable, otherwise use rootconstASSET_PATH= process.env.ASSET_PATH||'/';exportdefault{ output:{ publicPath:ASSET_PATH,}, plugins:[// This makes it possible for us to safely use env vars on our codenewwebpack.DefinePlugin({'process.env.ASSET_PATH':JSON.stringify(ASSET_PATH),}),],};Another possible use case is to set thepublicPath on the fly. Webpack exposes a global variable called__webpack_public_path__ that allows you to do that. In your application's entry point, you can do this:
__webpack_public_path__= process.env.ASSET_PATH;That's all you need. Since we're already using theDefinePlugin on ourconfiguration,process.env.ASSET_PATH will always be defined so we can safelydo that.
Be aware that if you use ES6 module imports in your entry file the__webpack_public_path__ assignment will be done after the imports. In such cases, you'll have to move the public path assignment to its own dedicated module and then import it on top of your entry.js:
// entry.jsimport'./public-path';import'./app';There are chances that you don't know what the publicPath will be in advance, and webpack can handle it automatically for you by determining the public path from variables likeimport.meta.url,document.currentScript,script.src orself.location. What you need is to setoutput.publicPath to'auto':
webpack.config.js
module.exports={ output:{ publicPath:'auto',},};Note that in cases wheredocument.currentScript is not supported, e.g., IE browser, you will have to include a polyfill likecurrentScript Polyfill.