画像を再構築する
rehype-image-salt
は <img>
タグを再構築する機能があります。
unified または nuxt-content のプラグインとして登録することで、<img>
タグに各種属性を設定したり <nuxt-img>
などへ置き換えることに利用できます。
unified
Markdown から HTML へ変換するときにプラグインとして利用している例です。
import { unified } from 'unified'
import rehypeParse from 'rehype-parse'
import remarkToRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import imageSalt from '@hankei6km/rehype-image-salt'
const rebuild = async (source: string) => {
const html = await unified()
.use(remarkParse)
.use(remarkToRehype)
.use(imageSalt, { command: 'rebuild', rebuild: { /* options... */ } })
.use(rehypeStringify)
.freeze()
.process(source)
return String(html)
}
console.log(
await rebuild('{width="600" height="400"}')
)
// <p><img src="/path/to/image.jpg" alt="river" width="600" height="400"></p>
nuxt-content
nuxt-content で利用する場合は、以下のようにプラグインの設定に追加します。
nuxt.config.js
{
content: {
markdown: {
rehypePlugins: [
[
"@hankei6km/rehype-image-salt",
{
baseURL: "https://.../",
rebuild: {
// options...
},
},
],
],
},
},
}
オプション
以下のオブジェクトでオプションを指定します。配列にすることで複数のオプションを適用できます(内部的には再構築が複数回実行されます)。
command
- Type:
rebuild | embed
- Default:
rebuild
プラグインとして稼働するときのモードを指定。再構築時にはreuild
を指定する。
baseURL
- Type:
string
- Default:
none
再構築の対象とする画像 URL のベース部分を指定。再構築後に画像 URL から取り除かれる。
rebuild.tagName
- Type:
string
- Default:
img
再構築時に利用するタグ名。
rebuild.keepBaseURL
- Type:
boolean
- Default:
true
再構築時に画像 URL 内の baseURL
部分を残すか指定。tagName
に nuxt-image 用タグ(nuxt-img
など)を指定するとデフォルト値が false
となる。
rebuild.baseAttrs
- Type:
string
- Default:
``
デフォルトの属性を記述。