首页 > 解决方案 > WP5 模块联合:remoteEntry.js 缓存

问题描述

使用 Webpack 5 模块联合,如果远程条目被修改,您不需要重新部署主模块/应用程序,并且当浏览器请求时将加载最新版本的模块。

我想知道:由于远程 URL 保持不变(例如http://localhost:8081/remoteEntry.js),浏览器可能会在每次加载主模块时缓存文件和缓存版本。另一方面,如果您为远程条目添加缓存清除,您将没有缓存。

让我们假设有一个使用 Webpack 5 模块联合的微前端架构的应用程序。有一个远程微前端,其配置如下:

output: {
  publicPath: "http://localhost:8081/",
},
plugins: [
  new ModuleFederationPlugin({
    name: "app1",
    filename: "remoteEntry.js",
    exposes: {
      "./Component1": "./src/Component1",
      "./someModule1": "./src/someModule1",
    },
  })
]

然后是主模块配置:

output: {
  publicPath: "http://localhost:8080/",
},
plugins: [
  new ModuleFederationPlugin({
    name: "mainApp",
    filename: "remoteEntry.js",
    remotes: {
      app1: "app1@http://localhost:8081/remoteEntry.js"
    }
  })
]

这两个模块都部署在生产环境中。

然后我更改Component1app1部署app1模块。

如何处理远程模块缓存?

更新:

在我的情况下,浏览器似乎使用启发式缓存(https://www.rfc-editor.org/rfc/rfc7234#section-4.2.2),remoteEntry.js因为服务器没有提供明确的到期时间。

因此,当remoteEntry.js更新时,主应用程序仍会从可能缓存数周的缓存中加载此文件。对于块,这不是问题,因为 webpack 可以配置为在文件名中包含哈希。

因为remoteEntry.js我看到了 2 个选项:

你认为这是一条路吗?

标签: javascriptmicro-frontendwebpack-5webpack-module-federation

解决方案


缓存破坏意味着重新构建(或至少后处理)主应用程序包,这是模块联合试图避免的问题之一。

因此,考虑到remoteEntry.js通常是一个小文件,最好的解决方案是对该文件应用特定的缓存控制,使其永远不会被缓存。

使用 nginx,可以这样做:

location ~ .*remoteEntry.js$ {
    expires -1;
    add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
}

推荐阅读