AMP

示例

通过 Next.js,您只需极简配置,无需脱离 React 即可将任意 React 页面转换为 AMP 页面。

您可以在官方 amp.dev 站点了解更多关于 AMP 的信息。

启用 AMP

要为页面启用 AMP 支持并了解不同的 AMP 配置选项,请阅读 next/amp 的 API 文档

注意事项

添加 AMP 组件

AMP 社区提供了众多组件来增强 AMP 页面的交互性。Next.js 会自动导入页面中使用的所有组件,无需手动导入 AMP 组件脚本:

export const config = { amp: true }

function MyAmpPage() {
  const date = new Date()

  return (
    <div>
      <p>当前时间: {date.toJSON()}</p>
      <amp-timeago
        width="0"
        height="15"
        datetime={date.toJSON()}
        layout="responsive"
      >
        .
      </amp-timeago>
    </div>
  )
}

export default MyAmpPage

上述示例使用了 amp-timeago 组件。

默认情况下,总是会导入组件的最新版本。如需自定义版本,可以使用 next/head,如下例所示:

import Head from 'next/head'

export const config = { amp: true }

function MyAmpPage() {
  const date = new Date()

  return (
    <div>
      <Head>
        <script
          async
          key="amp-timeago"
          custom-element="amp-timeago"
          src="https://cdn.ampproject.org/v0/amp-timeago-0.1.js"
        />
      </Head>

      <p>当前时间: {date.toJSON()}</p>
      <amp-timeago
        width="0"
        height="15"
        datetime={date.toJSON()}
        layout="responsive"
      >
        .
      </amp-timeago>
    </div>
  )
}

export default MyAmpPage

AMP 验证

在开发过程中,AMP 页面会通过 amphtml-validator 自动验证。错误和警告将显示在启动 Next.js 的终端中。

静态 HTML 导出时也会进行验证,任何警告/错误将打印到终端。任何 AMP 错误都会导致导出以状态码 1 退出,因为导出的内容不是有效的 AMP。

自定义验证器

您可以在 next.config.js 中设置自定义 AMP 验证器,如下所示:

module.exports = {
  amp: {
    validator: './custom_validator.js',
  },
}

跳过 AMP 验证

要关闭 AMP 验证,请在 next.config.js 中添加以下代码:

experimental: {
  amp: {
    skipValidation: true
  }
}

静态 HTML 导出中的 AMP

当使用静态 HTML 导出预渲染页面时,Next.js 会检测页面是否支持 AMP 并据此调整导出行为。

例如,混合 AMP 页面 pages/about.js 将输出:

  • out/about.html - 包含客户端 React 运行时的 HTML 页面
  • out/about.amp.html - AMP 页面

如果 pages/about.js 是纯 AMP 页面,则将输出:

  • out/about.html - 优化后的 AMP 页面

Next.js 会自动在 HTML 版本中插入指向 AMP 版本页面的链接,无需手动操作,如下所示:

<link rel="amphtml" href="/about.amp.html" />

而 AMP 版本的页面会包含指向 HTML 页面的链接:

<link rel="canonical" href="/about" />

当启用 trailingSlash 时,pages/about.js 导出的页面将为:

  • out/about/index.html - HTML 页面
  • out/about.amp/index.html - AMP 页面

TypeScript

AMP 目前没有为 TypeScript 提供内置类型,但已在路线图中 (#13791)。

作为临时解决方案,您可以在项目中手动创建名为 amp.d.ts 的文件并添加这些自定义类型

On this page