React.JS SSR 的 CDN 缓存

CDN caching for React.JS SSR

我有下面的代码来做我的服务器端渲染:

// Load in our HTML file from our build
fs.readFile(
  path.resolve(__dirname, '../build/index.html'),
  'utf8',
  (err, htmlData) => {
    // If there's an error... serve up something nasty
    ...
    // Pass all this nonsense into our HTML formatting function above
    const html = injectHTML(htmlData, {
      html: helmet.htmlAttributes.toString(),
      title: helmet.title.toString(),
      meta: helmet.meta.toString(),
      headScript: helmet.script.toString(),
      link: helmet.link.toString(),
      body: routeMarkup,
      scripts: extraChunks,
      state: JSON.stringify(store.getState()).replace(/</g, '\u003c')
    });
    // We have all the final HTML, let's send it to the user already!
    res.send(html);

它工作正常。但是,我所有的静态资产都是从 ../build 加载的。我想连接一个 CDN,比如 S3 来缓存资产。

为此,我需要将 CDN url 添加到静态资产链接的前面,以便 <script src="/static/js/main.7e3b844f.chunk.js"></script> 变为 <script src="https://cdn.mydomain.com/static/js/main.7e3b844f.chunk.js"></script>

感兴趣的url在htmlData里面。我可以使用正则表达式将 /static/css 替换为 ${prefix}/static/css 并且 /static/js.

也是如此

有比 运行 正则表达式更好的选择吗?建议?

在注入 HTML 正文、元等之前,我最终做了以下操作:

const prefix =
  process.env.REACT_APP_STAGE === 'production'
    ? 'https://prod-cdn.mydomain.com'
    : '';
const processedHtmlData = htmlData.replace(
  /(\/static)/g,
  `${prefix}`
);
const html = injectHTML(processedHtmlData, {
  html: helmet.htmlAttributes.toString(),
  title: helmet.title.toString(),
  meta: helmet.meta.toString(),
  headScript: helmet.script.toString(),
  link: helmet.link.toString(),
  body: routeMarkup,
  scripts: extraChunks,
  state: JSON.stringify(store.getState()).replace(/</g, '\u003c')
});

有效。