From b55fd857e1bba3589c1d2f4c6ef652c8c2506f80 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 14 Nov 2025 13:20:46 -0600 Subject: [PATCH] Treat Vite `?url` imports as external ESM CDN links --- src/lib/build/esmPlugin.ts | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index 865b4888..c59768ff 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -243,14 +243,12 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { // Handle bare imports like "react" build.onResolve({ filter: /^[^./].*/ }, (args) => { - // HACK: https://github.com/esm-dev/esm.sh/issues/1217 - if (args.path === "yet-another-react-lightbox/styles.css") { - args.path = "yet-another-react-lightbox/dist/styles.css"; - } + const [path, query] = args.path.split("?"); + const params = new URLSearchParams(query); - const packageName = args.path.startsWith("@") - ? args.path.split("/").slice(0, 2).join("/") - : args.path.split("/")[0]; + const packageName = path.startsWith("@") + ? path.split("/").slice(0, 2).join("/") + : path.split("/")[0]; // If the importer is CSS, ignore (no JS deps) try { @@ -319,7 +317,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { } } - const packagePath = args.path.slice(packageName.length); + const packagePath = path.slice(packageName.length); const specifier = version ? `${cdnName}@${version}${packagePath}` : `${cdnName}${packagePath}`; @@ -339,6 +337,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { }; } + // https://vite.dev/guide/assets#explicit-url-imports + if (params.has("url")) { + return { + path: urlStr, + namespace: "esm-file-external", + }; + } + return { path: urlStr, namespace: "esm", @@ -440,6 +446,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { loader, }; }); + + // Convert `?url` imports to URL strings pointing to the ESM CDN + build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => { + return { + contents: `export default ${JSON.stringify(args.path)};`, + loader: "js", + }; + }); }, }; }