NNext.js 中文网 GitHub

支持不可变静态资源

在适配器中支持不可变静态资源

有关此功能面向最终用户的信息,请参阅 config.supportsImmutableAssets。

当启用 config.supportsImmutableAssets 时,Next.js 会在公共路径 /_next/static/immutable/* 下输出不可变的内容寻址静态资源。此前缀可用于在 CDN 层面将不可变静态资源与非不可变静态资源区分开来。

在运行时,这些不可变静态资源的请求不带 ?dpl 查询参数,因此它们存在于跨部署的共享命名空间中。您必须确保这些资源是不可变的,不会被更改(即使在新部署之后)或删除(只要还有使用它们的活动部署)。Next.js 可能会使用截断的较短内容哈希作为文件名,因此 outputs.staticFiles[].immutableHash 包含完整的内容哈希,可用于验证是否发生了哈希冲突。

如果您出于某种原因(例如检测到哈希冲突后)想要轮换哈希,可以使用 config.outputHashSalt 为内容哈希设置盐值。

请注意,您需要继续支持非不可变静态资源(它们可能在部署之间发生变化,并继续带 ?dpl 查询参数请求),例如 public 文件夹或较旧版本的 Next.js。

适配器实现#

您需要:

  1. 在 modifyConfig 中,将 config.supportsImmutableAssets 属性设置为 true(如果用户尚未将其设置为 false),以表明您支持部署不可变静态资源,并且
  2. 在 onBuildComplete 中,读取 outputs.staticFiles[].immutableHash 属性,以确定哪些静态资源是不可变的、必须在不带 ?dpl 查询参数的情况下请求。
my-adapter.js
/** @type {import('next').NextAdapter} */
const adapter = {
  name: 'my-custom-adapter',

  async modifyConfig(config, { phase }) {
    if (phase === 'phase-production-build') {
      config.supportsImmutableAssets =
        // 默认为 true,但允许用户选择退出
        config.supportsImmutableAssets ?? true

      // 可选地,为内容哈希传递盐值
      // config.outputHashSalt = getSaltForCurrentProject()
    }
    return config
  },

  async onBuildComplete({ outputs }) {
    for (const output of outputs.staticFiles) {
      if (output.immutableHash != null) {
        // 这必须可以在 `output.pathname` 处请求
        // 即使不带 `?dpl` 查询参数。
        uploadOrVerifyImmutableStaticAsset(
          output.filePath,
          output.pathname,
          output.immutableHash
        )
      } else {
        // 这是一个非不可变静态资源,将带
        // `?dpl` 查询参数请求,作用域限定于该部署。
        uploadStaticAsset(output.filePath, output.pathname)
      }
    }

    // 处理其他输出....
  },
}
Next.js 中文网