英文:
How to host Next JS built index.html separately from other static assets?
问题
我有一个Next JS单页应用(没有服务器端代码),在`next build`后,会像往常一样在`_next`文件夹中生成`index.html`以及其他静态资源(JS块、图像等)。请参考下面的图片查看文件夹结构。
我需要在商业产品的特定流程中呈现此单页应用程序。由于该环境的限制,我必须将`index.html`托管在该环境中,但必须将其他静态资源托管在其他地方(例如公共S3存储桶)。
只需将`index.html`中所有的*相对路径*更改为指向静态资源的*绝对路径*,这种设置是否可行?
例如:
原始的`index.html`中的相对URL:
```html
<script src="/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>
手动重写的绝对URL:
<script src="https://s3.amazonaws.com/my-public-bucket/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>
如果行不通,如何使这种分布式设置生效?
<details>
<summary>英文:</summary>
I have a Next JS SPA (no server-side code), which after `next build` produces `index.html` along with other static assets (JS chunks, images etc.) in the `_next` folder as usual. See image below for the folder structure.
[![build folder structure][1]][1]
I need to render this SPA during a particular flow of a commercial product. Due to constraints of that environment, I must host the `index.html` on that environment but must host the other static assets elsewhere (e.g. a public S3 bucket)
Will this kind of a setup work just by changing all *relative paths* inside `index.html` to *absolute paths* pointing to the static assets?
For e.g.
Original relative URL in `index.html`:
<script src="/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>
Manually rewritten absolute URL:
<script src="https://s3.amazonaws.com/my-public-bucket/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>
If not, how to make this kind of a distributed setup work?
[1]: https://i.stack.imgur.com/gESC9.png
</details>
# 答案1
**得分**: 0
感谢Vercel工程师指向了我这个配置:
```javascript
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
// 在生产环境中使用CDN,在开发环境中使用本地主机。
assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined,
}
参考链接:https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix
英文:
Thanks to the Vercel engineer who pointed me to this config:
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
// Use the CDN in production and localhost for development.
assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined,
}
Ref: https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论