diff --git a/src/lib/build/esmShPlugin.ts b/src/lib/build/esmShPlugin.ts index db5861e9..ff6524d7 100644 --- a/src/lib/build/esmShPlugin.ts +++ b/src/lib/build/esmShPlugin.ts @@ -1,14 +1,29 @@ import type { Plugin } from 'esbuild-wasm'; -export function esmShPlugin(): Plugin { +export function esmShPlugin(dependencies: Record): Plugin { return { name: 'esm-sh', setup(build) { // Handle bare imports like "react" - build.onResolve({ filter: /^[^./].*/ }, (args) => ({ - path: `https://esm.sh/${args.path}`, - namespace: 'http', - })); + build.onResolve({ filter: /^[^./].*/ }, async (args) => { + const packageName = args.path.startsWith('@') + ? args.path.split('/').slice(0, 2).join('/') + : args.path.split('/')[0]; + + const version = dependencies[packageName]; + const packagePath = args.path.slice(packageName.length); + + if (version) { + const specifier = packagePath + ? `${packageName}@${version}${packagePath}` + : `${packageName}@${version}`; + + return { + path: `https://esm.sh/${specifier}`, + namespace: 'http', + }; + } + }); // Handle relative or absolute imports inside esm.sh modules build.onResolve({ filter: /.*/, namespace: 'http' }, (args) => { diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 963f0864..1213bb1e 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -12,6 +12,7 @@ await esbuild.initialize({ export async function buildProject(fs: JSRuntimeFS, projectId: string): Promise> { const indexHtml = await fs.readFile(`/projects/${projectId}/index.html`, 'utf8'); + const packageJson = await fs.readFile(`/projects/${projectId}/package.json`, 'utf8'); // Parse index.html to find the main script entry point const entryPoints = parseEntryPoints(indexHtml); @@ -29,7 +30,7 @@ export async function buildProject(fs: JSRuntimeFS, projectId: string): Promise< jsx: 'automatic', plugins: [ lightningFsPlugin(fs, `/projects/${projectId}/src`), - esmShPlugin(), + esmShPlugin(JSON.parse(packageJson).dependencies || {}), ], });