Treat Vite ?url imports as external ESM CDN links

This commit is contained in:
Alex Gleason committed 2025-11-14 13:20:46 -06:00
1 parent 65c51e865a
commit b55fd857e1
1 file changed
+22 -8
+22 -8
View File
@@ -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",
};
});
},
};
}