关于Angular 7.2.4生成Google AMP页面的可行性及成功案例问询
当然可以!我身边不少开发者都用Angular 7.2.4成功做出过符合规范的简单AMP页面,核心就是要适配AMP的严格规则,同时避开Angular默认的一些“不符合AMP”的特性。下面是具体的实现思路和步骤:
核心实现步骤
- 禁用Angular的客户端渲染冗余特性:AMP不允许自定义JS(除了官方指定的AMP脚本),所以得先把Angular的Zone.js关掉,避免生成不必要的客户端脚本。你可以在
main.ts里修改引导代码:platformBrowserDynamic().bootstrapModule(AppModule, { ngZone: 'noop' }) .catch(err => console.error(err)); - 剔除不符合AMP的Angular特性:像
routerLink、*ngIf、*ngFor这类会触发客户端JS的指令都不能用,要换成纯静态的HTML结构。如果需要动态内容,得用Angular Universal做服务器端预渲染,把最终的静态HTML输出给AMP。 - 严格遵循AMP的页面结构规范:
- 页面头部必须引入AMP核心脚本:
<script async src="https://cdn.ampproject.org/v0.js"></script> - 替换所有非AMP标签:比如把普通的
<img>换成<amp-img>,<video>换成<amp-video>,还要给这些标签设置明确的width/height,或者用layout="responsive"实现响应式适配。 - 所有样式必须放在
<style amp-custom>标签里,且总大小不能超过50KB,不能有内联样式。
- 页面头部必须引入AMP核心脚本:
- 用Angular Universal预渲染静态页面:AMP要求页面是纯静态的,所以最好用Angular Universal把你的Angular应用预渲染成静态HTML文件。在Angular 7.2.4里,你可以安装
@nguniversal/express-engine,配置好预渲染脚本后,就能生成完全符合AMP规则的静态页面了。 - 验证页面合规性:做完后别忘了用AMP的验证工具检查——在浏览器地址栏加上
#development=1,然后看控制台的AMP验证提示,把所有报错修复掉就行。
简单示例组件
这里有个极简的AMP页面组件示例,配合Universal预渲染就能正常工作:
import { Component } from '@angular/core'; @Component({ selector: 'app-simple-amp', template: ` <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <title>Angular 7.2.4 AMP Demo</title> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <script async src="https://cdn.ampproject.org/v0.js"></script> <style amp-custom> .container { max-width: 800px; margin: 0 auto; padding: 1rem; } h1 { color: #3498db; } </style> </head> <body class="container"> <h1>Hello Angular + AMP!</h1> <amp-img src="https://picsum.photos/800/450" alt="Sample AMP Image" width="800" height="450" layout="responsive" ></amp-img> </body> </html> `, styleUrls: [] }) export class SimpleAmpComponent {}
需要注意的是,这个组件不能直接用Angular的客户端渲染方式启动,必须通过Universal预渲染成静态HTML,否则会生成Angular的runtime JS,违反AMP的规则。
内容的提问来源于stack exchange,提问作者rcoenen
相关产品推荐
相关产品推荐

