如何在 SSR React 应用程序中将哈希添加到包名称

How to add hash to bundle name in 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。我可以编辑编译 bundle 的 webpack 配置,这样它会在名称中散列,但服务器代码不知道 bundle 的动态名称。

我有两个解决方案:

  1. 将插件添加到 webpack,这样它会生成模板(例如 .hbs)文件,其中已经插入了包名,然后在服务器上修改它以插入额外的数据(如元数据、内容等) .我不喜欢这个解决方案,因为它需要在每次请求时读取文件
  2. 在编译客户端的webpack配置中设置动态ENV变量,将其添加到bundle名称中,然后在服务器上的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')
  }
};

我不喜欢这个解决方案,因为它需要动态设置环境变量

朋友,使用这个插件,祝你快乐 https://github.com/ztoben/assets-webpack-plugin#configuration

也许你也可以试试这个插件react-ssr-webpack-plguin. It supports filename with hash, subresource integrity and inline the JS to html. It is done in one process with a tiny configuration. It also has live reload on save when both server and client JS have changes. You can this video