AMP

Node.js AMP Optimizer 指南

本指南說明如何設定及使用 Node.js 版本的 AMP Optimizer。

設定

使用 NPM 安裝

npm install @ampproject/toolbox-optimizer

用法

AMP Optimizer API 接受 HTML 字串作為輸入,並傳回 HTML 字串的最佳化版本。基本用法如下:

const AmpOptimizer = require('@ampproject/toolbox-optimizer');

// create the AMP Optimizer instance
const ampOptimizer = AmpOptimizer.create();

const html = '<h1>Hello World!</h1>';

const optimizedHtml = await ampOptimizer.transformHtml(html);

在建置時建立最佳化的 AMP

對於靜態網站,最好在建置網站時於建置時最佳化 AMP 頁面。以下範例說明如何將其整合到基於 Gulp.js 的建置中。此範例新增了一個自訂轉換,可最佳化 src 資料夾內的所有 HTML 檔案

const {src, dest} = require('gulp');
const through2 = require('through2');

const AmpOptimizer = require('@ampproject/toolbox-optimizer');
const ampOptimizer = AmpOptimizer.create();

function build(cb) {
  return src('src/*.html')
    .pipe(
      through2.obj(async (file, _, cb) => {
        if (file.isBuffer()) {
          const optimizedHtml = await ampOptimizer.transformHtml(
            file.contents.toString()
          );
          file.contents = Buffer.from(optimizedHtml);
        }
        cb(null, file);
      })
    )
    .pipe(dest('dist/'));
}

exports.default = build;

渲染時

對於動態頁面,通常需要在伺服器上渲染頁面。在這種情況下,您可以在渲染頁面後執行 AMP Optimizer。以下是整合到 Express.js 伺服器的範例。將 AMP 最佳化整合到 Express 路由器的其中一種方法是在範本 渲染後於回呼中執行它

const express = require('express');
const router = express.Router();
const AmpOptimizer = require('@ampproject/toolbox-optimizer');
const ampOptimizer = AmpOptimizer.create();

router.get('/', (req, res) => {
  const locals = {title: 'Express with AMP Optimizer'};
  res.render('index', locals, async (err, html) => {
    const optimizedHtml = await ampOptimizer.transformHtml(html);
    res.send(optimizedHtml);
  });
});

module.exports = router;

在伺服器上使用 AMP Optimizer 時,請務必設定快取或 CDN,以避免渲染延遲。

設定

AMP Optimizer 提供合理的預設設定,在大多數情況下應能良好運作。但是,轉換可以針對特定使用案例進行自訂。您可以在此處找到所有可用選項的清單。

幾個值得注意的選項包括

  • lts: true 用於為 AMP 執行階段和元件啟用長期穩定網址
  • verbose: true 用於詳細的偵錯輸出。特別適用於識別 AMP 樣板無法移除的原因。
  • imageOptimizer:透過提供函數來計算給定圖片 src 的 srcset 網址,啟用自動圖片 srcset 產生。此函數應傳回指向具有指定寬度的 src 圖片版本的網址。如果沒有圖片可用,則應傳回 falsy 值。更多資訊請參閱下一節。

圖片最佳化

AMP Optimizer 可以根據給定的 amp-img 的版面配置定義產生 srcset 值。為了使其運作,您需要提供一個函數,將圖片的 srcwidth 對應到調整大小的 srcset 來源值。圖片大小調整不是由 AMP Optimizer 執行,需要於建置時(例如,對於靜態網站)或透過圖片託管服務(例如 thumbor)進行。

以下是一個範例實作,將圖片寬度附加到 src

const ampOptimizer = AmpOptimizer.create({
  // parameters are the amp-img `src` and the `width` of the to be generated srcset source value
  imageOptimizer: (src, width) => {
    // we cannot rename if the image does not have a file extension
    const index = src.lastIndexOf('.');
    if (index === -1) {
      // return null means we won't generate a srcset source value for this width
      return null;
    }
    const prefix = src.substring(0, index);
    const postfix = src.substring(index, src.length);
    return `${prefix}.${width}w${postfix}`;
  };
})

使用此實作,AMP Optimizer 將轉換以下 amp-img 宣告

<!-- Injects srcset for responsive layout -->
<amp-img
  src="image1.png"
  width="400"
  height="800"
  layout="responsive"
  alt="..."
></amp-img>
<!-- Ignores existing srcset -->
<amp-img
  layout="fill"
  alt="..."
  srcset="image-1x.png 1x, image-2x.png 2x"
></amp-img>

<!-- Injects srcset for responsive layout -->
<amp-img
  src="image1.png"
  width="400"
  height="800"
  layout="responsive"
  alt="..."
  srcset="image1.470w.png 470w, image1.820w.png 820w, image1.1440w.png 1440w"
></amp-img>
<!-- Ignores existing srcset -->
<amp-img
  layout="fill"
  alt="..."
  srcset="image-1x.png 1x, image-2x.png 2x"
></amp-img>

使用 layout=responsive 時,請使用 widthheight 屬性來指定最小圖片尺寸。例如,對於行動裝置上的全出血英雄圖片,請將寬度指定為 width=320