webpack-dev-server path publicpath configuration when index.html is in different folders

Viewed 3201

I have tried to solve this using path, publicpath, contentBased but no luck. (only working if bundle.js and index.html are in same folder)

Env: Webpack 5 + webpack-dev-server + react.

Issue: unable to load application properly in wp dev server, either it show contents folders or not hot reload.
This working fine if generate html & bundle in same folder, but for some reason, I have to keep them in different folders.

Folder structure

dist\bundle.js
dist\style.css
public\index.html   (generated by HTML-webpack-plugin)
public\....         (other files)

webpack config

output: {
   path: path.resolve(..., 'dist')     //also tried to generate dist inside public
   filename: bundle.js
   //publicPath: path.resolve(..., 'dist') //etc
}
devServer: {
  contentBase: path.resolve(..., 'public')
}

I have tried multiple combination with no luck, I want to keep single version of html file and avoid modify src manually for dev builds.

Could someone please guide with right configuration.

1 Answers

contentBase accepts an array, like so:

module.exports = {
  // ...
  devServer: {
    // ...
    contentBase: [
      path.join(RootPath, 'public'),
      path.join(RootPath, 'dist')
    ]
    // ...
  }
  // ...
};

One important thing to note is that output.publicPath also plays a crucial role here.

By default (given your target is web (default) or webWorker), output.publicPath is set to 'auto', which means that it determines the url to fetch chunks based on how you require bundle.js. That'll work fine in most cases.

However, if your bundle.js itself is retrieved using an obscure relative path (e.g. the OP retrieves it from ../dist/bundle.js), then 'auto' will not work, and you probably want to set output.publicPath manually, using an absolute path (as the OP also ended up doing).

Related