img2amp-img is npm package of img convert to amp-img
I have recently created and released a new npm package.
This is a very simple tool that will convert HTML img tags into amp-img tags.
I needed to convert the amp-imp tag in the build process of Habanero Bee, an AMP-compatible static site generator that I'm developing myself.
I've written about Habanero Bee in this post, and I hope you'll read it.
Habanero Bee using to your content to the world faster!
Yuki Shindo ・ Mar 15 '21
However, to complete the conversion of the amp-img, it is not simply a matter of converting the tag string.
As described in the amp-img documentation, you need to specify the image size.
So I decided to fetch the target image and get its size during the conversion.
This strategy seems to be working well so far.
However, there are still very few use cases, so it will be interesting to see what happens when the patterns are used in unusual ways.
Of course, this tool is open source and available to the public. If you are interested in it, please take a look at the repository.
How to use img2amp-img
I would like to write about the usage of img2amp-img at the end.
img2amp-img is a tool that is designed to be used in a Node.js environment.
Note that this tool cannot be used in the frontend. It is used on the server side.
Install
npm install img2amp-img
# or
yarn add img2amp-img
Usage
const img2AmpImg = require('img2amp-img');
(async () => {
const imageTag = '<img src="https://dummyimage.com/200x100" alt="sample image" />';
const ampImgTag = await img2AmpImg(imageTag);
console.log(ampImgTag);
})();
The output of this code will look like this.
<amp-img
alt="sample image"
src="https://dummyimage.com/200x100"
width="200"
height="100"
layout="responsive"
></amp-img>
layout option
It is also possible to specify the layout attribute of amp-img. If nothing is specified, responsive
will be specified.
'responsive'
'fill'
'fixed'
'fixed-height'
'flex-item'
'intrinsic'
'nodisplay'
layout option example
const img2AmpImg = require('img2amp-img');
(async () => {
const imageTag = '<img src="https://dummyimage.com/200x100" alt="sample image" />';
const ampImgTag = await img2AmpImg(imageTag, 'fixed-height');
console.log(ampImgTag);
})();
For example, if you specify fixed-height
as an option, the output will look like the following.
<amp-img
alt="sample image"
src="https://dummyimage.com/200x100"
width="auto"
height="100"
layout="fixed-height"
></amp-img>
For more information about the option, please refer to the official AMP website.
amp-img - amp.dev
If you get a chance, try it.
Thank you for reading to the end!
Top comments (0)