From 86dfc0ef5c3704b1e375e68cac1bcaaf45206f2b Mon Sep 17 00:00:00 2001 From: Yuhanawa <74097164+Yuhanawa@users.noreply.github.com> Date: Sat, 7 Dec 2024 18:20:18 +0800 Subject: [PATCH] Store theme config in globalThis for virtual imports(#176)(#32) - add function example usage in playground config --- package/src/index.ts | 3 +- playground/astro.config.mts | 7 +++- tests/themes/theme-playground/index.ts | 1 + .../theme-playground/src/layouts/Layout.astro | 34 ++++++++++++------- 4 files changed, 30 insertions(+), 15 deletions(-) diff --git a/package/src/index.ts b/package/src/index.ts index 463596b..c36a483 100644 --- a/package/src/index.ts +++ b/package/src/index.ts @@ -118,9 +118,10 @@ export default function ( const projectRoot = resolveDirectory("./", config.root); + (globalThis as any)[themeName] = { userConfig, userConfigPartial }; // Record of virtual imports and their content const virtualImports: Parameters[0]["imports"] = { - [`${themeName}:config`]: `export default ${JSON.stringify(userConfig)}`, + [`${themeName}:config`]: `export default globalThis["${themeName}"].userConfig;`, [`${themeName}:context`]: "", }; diff --git a/playground/astro.config.mts b/playground/astro.config.mts index cc1c39a..0914d92 100644 --- a/playground/astro.config.mts +++ b/playground/astro.config.mts @@ -11,7 +11,12 @@ export default defineConfig({ config: { title: "Hey!", description: "This is a theme created using", - // sitemap: false + // sitemap: false, + customCornerMessage: (url: URL) => { + if (url.pathname === "/") return "you are on home page"; + if (url.pathname.startsWith("/cats")) return `you are on cats page, it's cute!`; + return `current url: ${url}`; + }, }, pages: { // '/cats': '/dogs', diff --git a/tests/themes/theme-playground/index.ts b/tests/themes/theme-playground/index.ts index 7e700ee..6c3b4a7 100644 --- a/tests/themes/theme-playground/index.ts +++ b/tests/themes/theme-playground/index.ts @@ -8,6 +8,7 @@ export default defineTheme({ title: z.string(), description: z.string().optional(), sitemap: z.boolean().optional().default(true), + customCornerMessage: z.function().args(z.instanceof(URL)).returns(z.string()).optional(), }), imports: { test: { diff --git a/tests/themes/theme-playground/src/layouts/Layout.astro b/tests/themes/theme-playground/src/layouts/Layout.astro index bc2e8b1..38028b2 100644 --- a/tests/themes/theme-playground/src/layouts/Layout.astro +++ b/tests/themes/theme-playground/src/layouts/Layout.astro @@ -1,20 +1,28 @@ --- import "theme-playground:styles"; +import config from "theme-playground:config"; --- - - - - - - - Theme - - - {Astro.url.pathname !== '/' && Home} -
+ + + + + + Theme + + + {Astro.url.pathname !== "/" && Home} + {config.customCornerMessage?.(Astro.url) ?? `current url: ${Astro.url}`} +
-
- +
+ +