Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force webpack to generate dynamic publicPath for resources

Tags:

webpack

I'm trying to figure out how to implement a MicroFrontend Host application that would be able to bootstrap one or more React applications built with webpack. For that purpose I need to force the application to load its resources from some different URL - and not just using relative paths.

Webpack has a nice feature for setting the public path: https://webpack.js.org/guides/public-path/ However there are some limitations:

  • if I don't apply it at build time then everything that is rendered in the index.html file will not have it included
  • it is a global variable which makes it unusable for my case - I cannot set two different values for two different micro frontends

Is there any way to make such a public url dynamic for an application built with webpack? I can live with the fact that I will have to manually update all urls in index.html, but then all the other resources (images, etc) I'd like to be able to get from some other URL. This is in general similar to hosting all the resources generated by webpack on a CDN and having index.html still served from a web server with a different address.

like image 325
kubal5003 Avatar asked Nov 06 '22 10:11

kubal5003


1 Answers

I think this feature should be configured on your frontend server (nginx/apache/node), not webpack.
It looks like you just need a proxy configuration for it. Example for webpack-dev-server, you can try something like this on localhost:

devServer: {
  proxy: [{
    {
      context: '/my/backend',
      target: `${PROTOCOL}://${HOST}:${PORT}`,
      pathRewrite: {'^/app1/images': '/shared/images'}
    },
    {
      context: '/my/backend',
      target: `${PROTOCOL}://${HOST}:${PORT}`,
      pathRewrite: {'^/app2/images': '/shared/images'}
    },
    {
      context: '/my/backend',
      target: `${PROTOCOL}://${HOST}:${PORT}`,
      pathRewrite: {'^/app1/sounds': '/shared/sounds'}
    },
    {
      context: '/my/backend',
      target: `${PROTOCOL}://${HOST}:${PORT}`,
      pathRewrite: {'^/app2/sounds': '/path/to/cdn'}
    }]
}

It is pseudocode, do not try this at home, but you got the idea.
Code and rules depends on server you choose of course.

PS. But it is very interesting question, I will try to find some solution with webpack.

like image 166
nickbullock Avatar answered Jan 01 '23 06:01

nickbullock