简体   繁体   English

如何在 Next.js 中设置预加载头文件?

[英]How do I set preload headers in Next.js?

How do I set preload headers in Next.js when the files have random build names?当文件具有随机构建名称时,如何在 Next.js 中设置预加载标头?

I've seen from the page source that the static files are preloaded using link tags in the html.我从页面源代码中看到 static 文件是使用 html 中的链接标签预加载的。 I'd much rather have these preloaded in the headers, as that also enables HTTP/2 Server Push.我宁愿将这些预加载在标头中,因为这也启用了 HTTP/2 服务器推送。

According to the documentation, you can set custom headers in next.config.js.根据文档,您可以在 next.config.js 中设置自定义标头。 This is fine, but the main problem is that the file names get random strings every build.这很好,但主要问题是文件名在每次构建时都会得到随机字符串。

For example, I've also got some local font files that I'd like to push, aswell as the CSS file generated by Tailwind.例如,我还有一些我想推送的本地字体文件,以及 Tailwind 生成的 CSS 文件。

How would you set preload headers for the resources in Next.js?您将如何为 Next.js 中的资源设置预加载标头?

EDIT:编辑:

I have managed to hardcode font files in the headers, as these get to keep their random names on rebuild.我已经设法在标题中对字体文件进行硬编码,因为这些文件可以在重建时保持它们的随机名称。 Tailwind CSS seems to be impossible to hardcode this way, as it gets a new name right after I rebuild. Tailwind CSS 似乎不可能以这种方式硬编码,因为它在我重建后立即获得了一个新名称。 I guess I could modify the build folder in that case, but both of these methods are less than ideal.我想在这种情况下我可以修改构建文件夹,但这两种方法都不太理想。

Why isn't this a more common issue with people using React/Next.js?为什么这不是使用 React/Next.js 的人更常见的问题? As far as I know, Using HTTP/2 Server Push makes everything much faster as long as the server supports it.据我所知,只要服务器支持,使用 HTTP/2 服务器推送可以让一切变得更快。

Here is a working (but is it efficient?) solution, requiring to setup an Apache2 or NGINX reverse proxy:这是一个有效的(但它有效吗?)解决方案,需要设置 Apache2 或 NGINX 反向代理:

  • Use a custom server .使用自定义服务器
  • Intercept the response body, search <link rel=preload> HTML tags, and set for each link a Link HTTP header.截取响应正文,搜索<link rel=preload> HTML 标签,并为每个链接设置一个Link HTTP header。 You could use this library .你可以使用这个
  • Configure the reverse proxy ( NGINX or Apache2 ) to automatically push resources by intercepting Link HTTP headers.配置反向代理( NGINXApache2 )通过拦截Link HTTP 头来自动推送资源。

See also: https://github.com/vercel/next.js/issues/2961另见: https://github.com/vercel/next.js/issues/2961

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM