Sponsor
ntab.devntab.dev 提升效率的新标签页组件
点击查看
Menu

AMP

示例

使用 Next.js,你可以将任何 React 页面转换为 AMP 页面,配置极少,并且无需离开 React。

你可以在官方 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 的文件,并添加这些自定义类型