Skip to content

Instantly share code, notes, and snippets.

@notcod
Last active March 28, 2024 06:12
Show Gist options
  • Save notcod/29634bd9575a09391b8778215dae056c to your computer and use it in GitHub Desktop.
Save notcod/29634bd9575a09391b8778215dae056c to your computer and use it in GitHub Desktop.
//import Logo from '../assets/logo.png?jsx';
//<Logo/>
function ImageJSX() {
const supportedExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.avif', '.tiff'];
return {
name: 'my-plugin',
transform(code: any, id: any) {
const parseId = (originalId: string) => {
const [pathId, query] = originalId.split('?');
const queryStr = query || '';
return {
originalId,
pathId,
query: queryStr ? `?${query}` : '',
params: new URLSearchParams(queryStr),
};
};
id = id.toLowerCase();
const { params, pathId } = parseId(id);
if (params.has('jsx')) {
const extension = path.extname(pathId).toLowerCase();
if (supportedExtensions.includes(extension)) {
if (!code.includes('srcSet')) {
console.error(`Image '${id}' could not be optimized to JSX`);
}
const index = code.indexOf('export default');
return (
code.slice(0, index) +
`
import { jsx, Fragment } from "react/jsx-runtime";
const PROPS = {srcSet, width, height};
export default function (props, key) {
return jsx(Fragment, {
children: jsx("img", {
...{decoding: 'async', loading: 'lazy'}, ...PROPS, ...props
})
}, key);
}`
);
}
}
return null;
},
};
}
vv
@notcod
Copy link
Author

notcod commented Mar 28, 2024

//vite-env.d.ts
declare module '*?jsx' {
const Cmp: React.FC<Optional<Omit<HTMLImageElement, 'src' | 'width' | 'srcSet' | 'height'>>>;
export default Cmp;
export const width: number;
export const height: number;
export const srcSet: string;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment