Skip to content

Instantly share code, notes, and snippets.

@Tetsuya-Minase

Tetsuya-Minase/img2amp-img.ts Secret

Last active Feb 3, 2021
Embed
What would you like to do?
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