Last active
March 28, 2024 06:12
-
-
Save notcod/29634bd9575a09391b8778215dae056c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//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;
}