From 1cc0d82a449af0d503052a1d405bf6e24cd31103 Mon Sep 17 00:00:00 2001 From: Patrick Pircher Date: Tue, 5 Nov 2024 13:47:08 +0100 Subject: [PATCH] fix test --- packages/vite/src/assets.ts | 5 +++-- packages/vite/src/scripts.ts | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/assets.ts b/packages/vite/src/assets.ts index 4f1b95b5b..18055aec0 100644 --- a/packages/vite/src/assets.ts +++ b/packages/vite/src/assets.ts @@ -44,8 +44,9 @@ export function assets(): Plugin { configureServer(server) { return () => { server.middlewares.use((req, res, next) => { - if (req.originalUrl && req.originalUrl.length > 1) { - const assetUrl = findPublicAsset(req.originalUrl.split('?')[0], resolverLoader.resolver); + const originalUrl = req.originalUrl.slice(server.config.base.length - 1); + if (originalUrl && originalUrl.length > 1) { + const assetUrl = findPublicAsset(originalUrl.split('?')[0], resolverLoader.resolver); if (assetUrl) { return send(req as Readable, assetUrl).pipe(res); } diff --git a/packages/vite/src/scripts.ts b/packages/vite/src/scripts.ts index de6e991b6..f6612edc2 100644 --- a/packages/vite/src/scripts.ts +++ b/packages/vite/src/scripts.ts @@ -26,11 +26,14 @@ export function scripts(params?: { include?: string[]; exclude?: string[] }): Pl } }); + let config: any = null; + return { name: 'embroider-scripts', enforce: 'pre', configResolved(resolvedConfig) { + config = resolvedConfig; optimizer = new ScriptOptimizer(resolvedConfig.root); }, @@ -47,7 +50,7 @@ export function scripts(params?: { include?: string[]; exclude?: string[] }): Pl // we don't do anything in `vite dev`, we only need to work in `vite // build` if (!context.server) { - return optimizer.transformHTML(htmlIn); + return optimizer.transformHTML(htmlIn, config.base); } }, }; @@ -123,16 +126,25 @@ class ScriptOptimizer { return fileParts.join('.'); } - transformHTML(htmlIn: string) { + transformHTML(htmlIn: string, baseUrl: string) { if (this.transformState?.htmlIn !== htmlIn) { let parsed = new JSDOM(htmlIn); let scriptTags = [...parsed.window.document.querySelectorAll('script')] as HTMLScriptElement[]; + let linkTags = [...parsed.window.document.querySelectorAll('link')] as HTMLLinkElement[]; + for (const linkTag of linkTags) { + if (linkTag.href.startsWith('/') && !linkTag.href.startsWith(baseUrl)) { + linkTag.href = baseUrl + linkTag.href.slice(1); + } + } for (let scriptTag of scriptTags) { if (scriptTag.type !== 'module') { let fingerprinted = this.emitted.get(scriptTag.src); if (fingerprinted) { scriptTag.src = fingerprinted; } + if (scriptTag.src.startsWith('/') && !scriptTag.src.startsWith(baseUrl)) { + scriptTag.src = baseUrl + scriptTag.src.slice(1); + } } } let htmlOut = parsed.serialize();