assetPrefix
注意力:部署到 Vercel 会自动为你的 Next.js 项目配置全局 CDN。你无需手动设置资源前缀。
¥Attention: Deploying to Vercel automatically configures a global CDN for your Next.js project. You do not need to manually setup an Asset Prefix.
很高兴知道:Next.js 9.5+ 添加了对可自定义 基本路径 的支持,它更适合在
/docs
这样的子路径上托管应用。我们不建议你为此用例使用自定义资源前缀。¥Good to know: Next.js 9.5+ added support for a customizable Base Path, which is better suited for hosting your application on a sub-path like
/docs
. We do not suggest you use a custom Asset Prefix for this use case.
设置 CDN
¥Set up a CDN
要设置 CDN,你可以设置资源前缀并配置 CDN 的来源以解析为托管 Next.js 的域。
¥To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on.
打开 next.config.mjs
并根据 phase 添加 assetPrefix
配置:
¥Open next.config.mjs
and add the assetPrefix
config based on the phase:
// @ts-check
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
export default (phase) => {
const isDev = phase === PHASE_DEVELOPMENT_SERVER
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
assetPrefix: isDev ? undefined : 'https://cdn.mydomain.com',
}
return nextConfig
}
Next.js 将自动使用你从 /_next/
路径(.next/static/
文件夹)加载的 JavaScript 和 CSS 文件的资源前缀。例如,使用上述配置,对 JS 块的请求如下:
¥Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the /_next/
path (.next/static/
folder). For example, with the above configuration, the following request for a JS chunk:
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
相反会变成:
¥Would instead become:
https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
将文件上传到给定 CDN 的确切配置取决于你选择的 CDN。你需要在 CDN 上托管的唯一文件夹是 .next/static/
的内容,应将其上传为 _next/static/
,如上述 URL 请求所示。不要上传 .next/
文件夹的其余部分,因为你不应该向公众公开你的服务器代码和其他配置。
¥The exact configuration for uploading your files to a given CDN will depend on your CDN of choice. The only folder you need to host on your CDN is the contents of .next/static/
, which should be uploaded as _next/static/
as the above URL request indicates. Do not upload the rest of your .next/
folder, as you should not expose your server code and other configuration to the public.
虽然 assetPrefix
覆盖了对 _next/static
的请求,但它不影响以下路径:
¥While assetPrefix
covers requests to _next/static
, it does not influence the following paths: