From 69d5b70900c6392bae1db89efcad57dbdcfa87da Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Fri, 28 Jan 2022 17:10:52 -0500 Subject: [PATCH] Fix use of preprocessors with the static build (#2490) * Fix use of preprocessors with the static build * Adds a changeset --- .changeset/hungry-dots-reply.md | 5 +++++ examples/fast-build/src/pages/index.astro | 6 ++++++ .../astro/src/vite-plugin-astro/compile.ts | 20 +++++++++++-------- 3 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 .changeset/hungry-dots-reply.md diff --git a/.changeset/hungry-dots-reply.md b/.changeset/hungry-dots-reply.md new file mode 100644 index 000000000..8dbb28001 --- /dev/null +++ b/.changeset/hungry-dots-reply.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix for CSS preprocessing using the static build diff --git a/examples/fast-build/src/pages/index.astro b/examples/fast-build/src/pages/index.astro index ef0136b27..24ec0039a 100644 --- a/examples/fast-build/src/pages/index.astro +++ b/examples/fast-build/src/pages/index.astro @@ -16,6 +16,12 @@ import ExternalHoisted from '../components/ExternalHoisted.astro'; color: salmon; } +
diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index d99c96f4a..be77b91c7 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -50,15 +50,18 @@ async function compile(config: AstroConfig, filename: string, source: string, vi experimentalStaticExtraction: config.buildOptions.experimentalStaticBuild, // TODO add experimental flag here preprocessStyle: async (value: string, attrs: Record) => { - // When using this flag CSS is added via and therefore goes - // through Vite's CSS pipeline. We don't need to transform here, it will be - // transformed on CSS requests. - if (config.buildOptions.experimentalStaticBuild) { - return { code: value }; - } - const lang = `.${attrs?.lang || 'css'}`.toLowerCase(); try { + let prefix = ''; + // In the static build, strip away at-imports so that they can be resolved + // by the pseudo-module that gets created. + if(config.buildOptions.experimentalStaticBuild) { + value = value.replace(/(?:@import)\s(?:url\()?\s?["\'](.*?)["\']\s?\)?(?:[^;]*);?/gi, (match) => { + prefix += match; + // Replace with an empty string of the same length, to preserve source maps. + return new Array(match.length).fill(' ').join(''); + }); + } const result = await transformWithVite({ value, lang, @@ -76,7 +79,8 @@ async function compile(config: AstroConfig, filename: string, source: string, vi map = result.map.toString(); } } - return { code: result.code, map }; + const code = prefix += result.code; + return { code, map }; } catch (err) { // save error to throw in plugin context cssTransformError = err as any;