如何在Remix中实现Google AMP支持?寻求高效解决方案
在Remix中实现Google AMP的可行方案
我们的服务需要支持Google AMP,了解到Next.js内置AMP支持,但Remix目前没有原生提供该功能,逐页手动创建AMP页面耗时太久,求可行实现方案。
可行实现方案
方案一:基于Remix社区讨论的基础规范实现
- 为AMP页面建立独立路由分组(例如
routes/amp目录下的所有路由),统一管控AMP页面的渲染逻辑 - 自定义AMP专用根布局,必须包含AMP要求的基础元标签与脚本:
<meta charset="utf-8"><meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"><script async src="https://cdn.ampproject.org/v0.js"></script>
- 在对应路由的
meta函数中返回{"amp": "google"}标识,确保页面被识别为AMP页面 - 避免使用Remix客户端交互API(如
clientLoader、useActionData),仅使用AMP官方提供的组件与脚本,符合AMP对自定义JS的严格限制
方案二:基于社区教程的封装式快速实现
- 封装AMP专用高阶组件(HOC),统一处理AMP页面的基础结构:
export function withAMP(Component) { return function AMPComponent(props) { return ( <html amp> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,minimum-scale=1" /> <script async src="https://cdn.ampproject.org/v0.js"></script> {/* 按需引入AMP组件脚本,如amp-img、amp-form等 */} </head> <body> <Component {...props} /> </body> </html> ); }; } - 在需要转为AMP的路由组件中使用该HOC包裹,并禁用Remix客户端 hydration:
import { withAMP } from "~/utils/amp"; function AMPProductPage() { return ( <div> {/* 使用AMP官方组件替代原生HTML元素,例如用<amp-img>代替<img> */} <amp-img src="/product.jpg" width="600" height="400" layout="responsive" alt="产品展示图" /> <h1>产品详情</h1> {/* 其他AMP兼容内容 */} </div> ); } export default withAMP(AMPProductPage); // 禁用客户端hydration,符合AMP页面要求 export function clientLoader() { return null; } - 通过路由参数或子路由区分AMP页面与普通页面,复用业务逻辑内容,减少重复开发
内容的提问来源于stack exchange,提问作者user14082
相关产品推荐
相关产品推荐

