|
| 1 | +import { path, Plugin } from "../../deps.ts"; |
| 2 | +import { createFilter } from "../deps.ts"; |
| 3 | +import { svgToMiniDataURI } from "./deps.ts"; |
| 4 | + |
| 5 | +const defaults = { |
| 6 | + dom: false, |
| 7 | + exclude: null, |
| 8 | + include: null, |
| 9 | +}; |
| 10 | + |
| 11 | +interface mimeTypesInterface { |
| 12 | + ".jpg": string; |
| 13 | + ".jpeg": string; |
| 14 | + ".png": string; |
| 15 | + ".gif": string; |
| 16 | + ".svg": string; |
| 17 | + ".webp": string; |
| 18 | + [key: string]: string; |
| 19 | +} |
| 20 | + |
| 21 | +const mimeTypes: mimeTypesInterface = { |
| 22 | + ".jpg": "image/jpeg", |
| 23 | + ".jpeg": "image/jpeg", |
| 24 | + ".png": "image/png", |
| 25 | + ".gif": "image/gif", |
| 26 | + ".svg": "image/svg+xml", |
| 27 | + ".webp": "image/webp", |
| 28 | +}; |
| 29 | + |
| 30 | +const domTemplate = ({ dataUri }: { dataUri: string }) => |
| 31 | + ` |
| 32 | + const img = new Image(); |
| 33 | + img.src = "${dataUri}"; |
| 34 | + export default img; |
| 35 | +`; |
| 36 | + |
| 37 | +const constTemplate = ({ dataUri }: { dataUri: string }) => |
| 38 | + ` |
| 39 | + const img = "${dataUri}"; |
| 40 | + export default img; |
| 41 | +`; |
| 42 | + |
| 43 | +type Opts = { |
| 44 | + dom?: boolean; |
| 45 | + exclude?: string | string[]; |
| 46 | + include?: string | string[]; |
| 47 | +}; |
| 48 | + |
| 49 | +const getDataUri = ( |
| 50 | + { format, isSvg, mime, source }: { |
| 51 | + format: string; |
| 52 | + isSvg: boolean; |
| 53 | + mime: string; |
| 54 | + source: string; |
| 55 | + }, |
| 56 | +) => isSvg ? svgToMiniDataURI(source) : `data:${mime};${format},${source}`; |
| 57 | + |
| 58 | +export function pluginImageLoader(opts: Opts = {}): Plugin { |
| 59 | + const options = Object.assign({}, defaults, opts) as Opts; |
| 60 | + const filter = createFilter(options.include, options.exclude); |
| 61 | + |
| 62 | + return { |
| 63 | + name: "denopack-plugin-imageLoader", |
| 64 | + async load(id) { |
| 65 | + if (!filter(id)) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + |
| 69 | + const mime = mimeTypes[path.extname(id)]; |
| 70 | + if (!mime) { |
| 71 | + // not an image |
| 72 | + return null; |
| 73 | + } |
| 74 | + |
| 75 | + const isSvg = mime === mimeTypes[".svg"]; |
| 76 | + const format = isSvg ? "utf-8" : "base64"; |
| 77 | + const decoder = new TextDecoder("utf-8"); |
| 78 | + const data = await Deno.readFile(new URL(id)); |
| 79 | + const source = decoder.decode(data).replace( |
| 80 | + /[\r\n]+/gm, |
| 81 | + "", |
| 82 | + ); |
| 83 | + const dataUri = getDataUri({ format, isSvg, mime, source }); |
| 84 | + const code = options.dom |
| 85 | + ? domTemplate({ dataUri }) |
| 86 | + : constTemplate({ dataUri }); |
| 87 | + return code.trim(); |
| 88 | + }, |
| 89 | + }; |
| 90 | +} |
| 91 | + |
| 92 | +export default pluginImageLoader; |
0 commit comments