Typescript refactoring
ramblehead opened this issue · comments
Victor Rybynok commented
Thank you for sharing rehype-img-size
!
I needed to do some additional transformations to src
attribute of img
tags and I am using typescript, so I have done a bit of refactoring to rehype-img-size
plugin:
import path from 'path';
import { visit } from 'unist-util-visit';
import sizeOf from 'image-size';
import type { Plugin } from 'unified';
import type { Node } from 'unist';
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const getImageSize = (src: string, dir: string) => {
// Handles "//" such as "http://" "https://" "ftp://"
if (src.match(/^(?:[a-z]+:)?\/\//)) {
return undefined;
}
// Treat `/` as a relative path, according to the server
const shouldJoin = !path.isAbsolute(src) || src.startsWith('/');
let srcPath = src;
if (dir && shouldJoin) {
srcPath = path.join(dir, src);
}
return sizeOf(srcPath);
};
interface TagNode extends Node {
tagName: '';
}
interface ImgNode extends Node {
tagName: 'img';
properties: {
src: string;
width: number;
height: number;
};
}
type ElementNode = TagNode | ImgNode;
type PluginParameters = [
{
dir: string;
},
];
const rehypeImgSize: Plugin<PluginParameters> = ({ dir }) => {
return (tree, _file) => {
visit(tree, 'element', (node: ElementNode) => {
if (node.tagName === 'img') {
const { src } = node.properties;
const dimensions = getImageSize(src, dir);
node.properties.width = dimensions?.width ?? 0;
node.properties.height = dimensions?.height ?? 0;
}
});
};
};
export default rehypeImgSize;
I wonder if there is an interest in updating this project to typescript either as the code above or in jsdoc syntax flavour? In either syntax typescript can automatically generate typings and replace some unit testes by compile-time checks.