Search code examples
webpackwebpack-dev-serverwebpack-4

Difference between publicPath and contentBase in webpack


I started using webpack and now confused between the publicPath and contentBase. The documentation isn't clear on the use case.


Solution

  • publicPath

    Exists in both webpack and webpack-dev-server. Keyword is Output!

    First webpack without dev-server:

    Say you have a domain example.com and you have your web-app at example.com/app/. Now normally, urls would be /bundle.abc123.js. But by changing the publicPath it can become /app/bundle.abc123.js.

    Dev-server

    Same thing as webpack. You can now run a devserver that serves at http://localhost:8080/app/ simple! It's only about where to output the files.

    contentBase

    Exists only in webpack-dev-server. It's only needed if you want to serve static files. For example, you want a folder of mp4 vacation movies to be available for the app, but you don't want to run them through the bundle, because that would be silly. Those asset files almost never change, but they need to be available for the app.

    contentBase: path.join(__dirname, 'movies')
    

    now you can use those from your app on your dev server

    <video src="/movies/vacation.mp4">
    

    So this controls what static files to add to your devserver. keyword Input!

    contentBasePublicPath

    And then last we have:

    contentBasePublicPath: '/assets'
    

    which is same as publicPath, but only for files you added using contentBase.

    <video src="/assets/movies/vacation.mp4">