Mike
Mike

Reputation: 6239

How to rewrite certain URLs in webpack-dev-server

I am creating a React & react-router v4 application bundled with Webpack. I am creating async split points with Webpack to async load bundles for react-router routes of my application on-demand.

Assuming my app is called "myapp", when I deploy this to my server my static assets need to be served from:

/myapp/static/<assetName>

In order for the async bundle loading to work when deploying to the server, my Webpack output config is as follows:

output: {
  path: path.resolve(__dirname, "build"),
  publicPath: "/myapp/static/",
  chunkFilename: "[name].[chunkhash].bundle.js",
  filename: "[name].[chunkhash].bundle.js"
}

In my devServer section I have this:

devServer: {
  historyApiFallback: true,
  inline: true,
  port: 4000,
  publicPath: "/myapp" // this is so my app is served from http://locahost:4000/myapp 
}

I don't have any issues when I actually deploy to my server, however when I run webpack-dev-server and I access:

http://localhost:4000/myapp

...the html is served up, but all the URLs generated for my bundles by HtmlWebpackPlugin are /myapp/static/<bundleName> and therefore fail to fetch as the bundles are being served at /mpapp/<bundleName>.

How can I configure webpack-dev-server to rewrite /myapp/static/<bundleName> to /myapp/<bundleName> so that it will route to the bundles that are actually being served locally under /myapp?

I've tried all manner of rewrite and proxy directives, but I just seem to break the app - I'm sure there's a simple way that I'm overlooking.

Many thanks.

Upvotes: 5

Views: 13438

Answers (1)

Hristo
Hristo

Reputation: 46467

Try setting the index for historyApiFallback like this:

historyApiFallback: {
  index: "/myapp/static/"
},

For more information, refer to the webpack and connect-history-api-fallback docs:

https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback https://github.com/bripkens/connect-history-api-fallback

Upvotes: 1

Related Questions