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>My AMP About Page!</h3>
}
export default About
上面的页面是一个仅 AMP 页面,这意味着
- 该页面没有 Next.js 或 React 客户端运行时
- 页面使用 AMP Optimizer自动优化,该优化器应用与 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>My AMP About Page!</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 Optimizer 优化,以便它可以被搜索引擎索引
页面使用 useAmp
来区分模式,它是一个 React Hook,如果页面正在使用 AMP,则返回 true
,否则返回 false
。
这有帮助吗?