-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f62f05f
commit d024fa7
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { Plugin as VitePlugin } from 'vite'; | ||
import { AstroConfig } from '../@types/astro.js'; | ||
import { PAGE_SSR_SCRIPT_ID } from './index.js'; | ||
|
||
import { resolvePages } from '../core/util.js'; | ||
import ancestor from 'common-ancestor-path'; | ||
import MagicString from 'magic-string'; | ||
|
||
export default function astroScriptsPostPlugin({ config }: { config: AstroConfig }): VitePlugin { | ||
function normalizeFilename(filename: string) { | ||
if (filename.startsWith('/@fs')) { | ||
filename = filename.slice('/@fs'.length); | ||
} else if (filename.startsWith('/') && !ancestor(filename, config.root.pathname)) { | ||
filename = new URL('.' + filename, config.root).pathname; | ||
} | ||
return filename; | ||
} | ||
|
||
return { | ||
name: 'astro:scripts:post', | ||
enforce: 'post', | ||
|
||
transform(this, code, id, options) { | ||
if (!options?.ssr) return; | ||
|
||
const filename = normalizeFilename(id); | ||
let fileUrl: URL; | ||
try { | ||
fileUrl = new URL(`file://${filename}`); | ||
} catch (e) { | ||
// If we can't construct a valid URL, exit early | ||
return; | ||
} | ||
|
||
const isPage = fileUrl.pathname.startsWith(resolvePages(config).pathname); | ||
if (!isPage) return; | ||
const parts = fileUrl.pathname.slice(resolvePages(config).pathname.length).split('/'); | ||
for (const part of parts) { | ||
if (part.startsWith('_')) return; | ||
} | ||
const hasInjectedScript = config._ctx.scripts.some((s) => s.stage === 'page-ssr'); | ||
if (!hasInjectedScript) return; | ||
|
||
const s = new MagicString(code, { filename }); | ||
s.prepend(`import '${PAGE_SSR_SCRIPT_ID}';\n`); | ||
|
||
return { | ||
code: s.toString(), | ||
map: s.generateMap(), | ||
} | ||
}, | ||
}; | ||
} |