markdown内の画像タグをamp-imgに変換する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unified from 'unified'; | |
import remarkParse from 'remark-parse'; | |
import remark2rehype from 'remark-rehype'; | |
import html from 'rehype-stringify'; | |
async function markdown2html(markdownText: string) { | |
const processedContent = await unified() | |
.use(remarkParse) | |
.use(remark2rehype) | |
.use(html) | |
.process(markdownText); | |
return processedContent.toString(); | |
} | |
function imageToAmpImage() { | |
return function (node: any, vfile: any, done: any) { | |
const children = node.children.map((child: any) => { | |
if (child.type === 'element' && child.tagName === 'p') { | |
const image = child.children.find((c: any) => c.type === 'element' && c.tagName === 'img'); | |
if (!image) { | |
return child; | |
} | |
const imagePath = image.properties.src; | |
const imageAlt = image.properties.alt; | |
const fallbackImage = { | |
...image, | |
tagName: 'amp-img', | |
properties: { | |
...image.properties, | |
width: 800, | |
height: 450, | |
media: '(min-width: 800px)', | |
fallback: true | |
} | |
}; | |
const fallbackImageSp = { | |
...image, | |
tagName: 'amp-img', | |
properties: { | |
...image.properties, | |
width: 320, | |
height: 180, | |
media: '(max-width: 450px)', | |
fallback: true | |
} | |
}; | |
const webpImage = { | |
type: 'element', | |
tagName: 'amp-img', | |
children: [fallbackImage], | |
properties: { | |
src: image.properties.src.replace(/\.png$/, '.webp'), | |
alt: imageAlt, | |
width: 800, | |
height: 450, | |
media: '(min-width: 800px)' | |
} | |
}; | |
const webpImageSp = { | |
type: 'element', | |
tagName: 'amp-img', | |
children: [fallbackImageSp], | |
properties: { | |
src: image.properties.src.replace(/\.png$/, '.webp'), | |
alt: imageAlt, | |
width: 320, | |
height: 180, | |
media: '(max-width: 450px)' | |
} | |
}; | |
child.children = [...child.children.filter((c: any) => c.type !== 'element' && c.tagName !== 'img'), webpImage, webpImageSp]; | |
} | |
return child; | |
}); | |
node.children = children; | |
done(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment