如何在SSR React App中将哈希添加到捆绑包名称

我有ssr应用,服务器上有代码(简体)

 const content = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.path} context={context}>
        <div>{renderRoutes(Routes)}</div>
      </StaticRouter>
    </Provider>
  );

 return `
    <html>
      <head>
      </head>
      <body>
        <div id="root">${content}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `;

问题是,想要将哈希添加到由webpack组成的bundle.js中。我可以编辑可编译包的webpack配置,以便它将名称散列,但服务器代码不知道包的动态名称。

我有两种解决方法:

  1. 将插件添加到webpack中,以便它将制作模板文件(例如.hbs),其中已插入包名称,然后在服务器上对其进行修改以插入其他数据(例如元数据,内容等)。我不喜欢这种解决方案,因为它将需要在每个请求上读取文件
  2. 在可编译客户端的webpack配置中设置动态ENV变量,将其添加到捆绑包名称中,然后在服务器上的ENV中访问
const crypto = require('crypto');
process.env.BUILD_HASH = crypto.randomBytes(20).toString('hex');
const BUILD_HASH = process.env.BUILD_HASH
console.log('building client')

const config = {
  output: {
    filename: `bundle_${BUILD_HASH}.js`,path: path.resolve(__dirname,'public')
  }
};

我不喜欢这种解决方案,因为它需要动态设置ENV var

bjwmkj 回答:如何在SSR React App中将哈希添加到捆绑包名称

朋友,请使用此插件并开心? https://github.com/ztoben/assets-webpack-plugin#configuration

本文链接:https://www.f2er.com/3051519.html

大家都在问