microCMSではリッチテキストエディタで作成したデータはHTMLタグで保存されています。
ブログの本文などをリッチテキストエディタで作成した場合、本文内の画像をレスポンシブ画像にしたり、WebPに変換して表示したい場合、取得したデータをパースして加工する必要があります。
やりたいこと
- ブログの本文内の画像をレスポンシブ画像で表示する。
- 画像をWebPフォーマットに変換する
ドキュメント
パッケージのインストール
npm install microcms-rich-editor-handler
私の環境では microcms-rich-editor-handler が利用する shiki も追加でインストールしました。パッケージが足りない場合はエラーが出るので、その内容に従ってインストールしましょう。
npm install npm install shiki
コード例
公式で配布されてるテンプレートに組み込む形で紹介します。
オリジナル
コードを追加した例
import { formatRichText } from '@/libs/utils';
import { type Article } from '@/libs/microcms';
import PublishedDate from '../Date';
import styles from './index.module.css';
import TagList from '../TagList';
import Profile from '../Profile';
// 1. microcms-rich-editor-handler と transformer をインポート
import {
microCMSRichEditorHandler,
responsiveImageTransformer,
} from 'microcms-rich-editor-handler';
type Props = {
data: Article;
};
// 2. microCMSRichEditorHandler が非同期関数なので、async function に変更
export default async function Article({ data }: Props) {
// 3. data.content(ブログの本文) に対してmicroCMSRichEditorHandlerを非同期で実行し、画像のレスポンシブ化を行う
const processedContent = data.content
? (
await microCMSRichEditorHandler(data.content, {
transformers: [
responsiveImageTransformer({
attributes: {
sizes: 'auto',
},
formats: ['default', 'webp'],
// デバイスサイズと本文部分のコンテンツ幅に合わせて指定
deviceSizes: [640, 750, 828, 1080, 1440],
}),
],
})
).html
: '';
return (
<main className={styles.main}>
<h1 className={styles.title}>{data.title}</h1>
<TagList tags={data.tags} />
<p className={styles.description}>{data.description}</p>
<div className={styles.meta}>
{data.writer && (
<div className={styles.writer}>
<picture>
<source
type="image/webp"
srcSet={`${data.writer?.image?.url}?fm=webp&fit=crop&w=48&h=48 1x, ${data.writer?.image?.url}?fm=webp&fit=crop&w=48&h=48&dpr=2 2x`}
/>
<img
src={data.writer?.image?.url}
alt=""
className={styles.writerIcon}
width={data.writer?.image?.width}
height={data.writer?.image?.height}
/>
</picture>
<span className={styles.writerName}>{data.writer?.name}</span>
</div>
)}
<PublishedDate date={data.publishedAt || data.createdAt} />
</div>
{data.thumbnail && (
<picture>
<source
type="image/webp"
media="(max-width: 640px)"
srcSet={`${data.thumbnail.url}?fm=webp&w=414 1x, ${data.thumbnail.url}?fm=webp&w=414&dpr=2 2x`}
/>
<source
type="image/webp"
srcSet={`${data.thumbnail.url}?fm=webp&fit=crop&w=960&h=504 1x, ${data.thumbnail.url}?fm=webp&fit=crop&w=960&h=504&dpr=2 2x`}
/>
<img
src={data.thumbnail.url}
alt=""
className={styles.thumbnail}
width={data.thumbnail.width}
height={data.thumbnail.height}
/>
</picture>
)}
{/* 4. 処理済みのHTML(processedContent)を渡す */}
<div
className={styles.content}
dangerouslySetInnerHTML={
processedContent ? { __html: processedContent } : undefined
}
/>
<Profile writer={data.writer} />
</main>
);
}
現場からは以上です。