useAmp

示例

AMP 支持是我们的高级功能之一,您可以在此处阅读更多关于 AMP 的内容

要启用 AMP,请向您的页面添加以下配置:

pages/index.js
export const config = { amp: true }

amp 配置接受以下值:

  • true - 页面将仅作为 AMP 页面
  • 'hybrid' - 页面将有两个版本,一个带有 AMP,另一个带有 HTML

要了解有关 amp 配置的更多信息,请阅读以下部分。

AMP 专属页面

请看以下示例:

pages/about.js
export const config = { amp: true }

function About(props) {
  return <h3>我的 AMP 关于页面!</h3>
}

export default About

上面的页面是一个 AMP 专属页面,这意味着:

  • 该页面没有 Next.js 或 React 的客户端运行时
  • 页面会自动通过 AMP 优化器 进行优化,该优化器应用与 AMP 缓存相同的转换(性能提升高达 42%)
  • 页面具有用户可访问的(优化)版本和搜索引擎可索引的(未优化)版本

混合 AMP 页面

请看以下示例:

pages/about.js
import { useAmp } from 'next/amp'

export const config = { amp: 'hybrid' }

function About(props) {
  const isAmp = useAmp()

  return (
    <div>
      <h3>我的 AMP 关于页面!</h3>
      {isAmp ? (
        <amp-img
          width="300"
          height="300"
          src="/my-img.jpg"
          alt="a cool image"
          layout="responsive"
        />
      ) : (
        <img width="300" height="300" src="/my-img.jpg" alt="a cool image" />
      )}
    </div>
  )
}

export default About

上面的页面是一个混合 AMP 页面,这意味着:

  • 页面会渲染为传统的 HTML(默认)和 AMP HTML(通过向 URL 添加 ?amp=1
  • 页面的 AMP 版本仅应用了 AMP 优化器的有效优化,以便被搜索引擎索引

该页面使用 useAmp 来区分模式,这是一个 React Hook,如果页面使用 AMP 则返回 true,否则返回 false

On this page