Skip to content

Instantly share code, notes, and snippets.

@Tetsuya-Minase
Last active February 3, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tetsuya-Minase/bb293590e6b26d0ae3452658d47e47a2 to your computer and use it in GitHub Desktop.
Save Tetsuya-Minase/bb293590e6b26d0ae3452658d47e47a2 to your computer and use it in GitHub Desktop.
markdown内の画像タグをamp-imgに変換する
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