From 2a45a3af897165c316e9b9e5fa5360354578c3b1 Mon Sep 17 00:00:00 2001 From: Jan Potoms <2109932+Janpot@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:10:10 +0200 Subject: [PATCH] [next] Wrap all generated CSS with a cascade layer (WIP) (#226) --- packages/pigment-css-unplugin/src/index.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/pigment-css-unplugin/src/index.ts b/packages/pigment-css-unplugin/src/index.ts index 9bc83051..45768174 100644 --- a/packages/pigment-css-unplugin/src/index.ts +++ b/packages/pigment-css-unplugin/src/index.ts @@ -26,7 +26,6 @@ import { } from '@pigment-css/react/utils'; import type { ResolvePluginInstance } from 'webpack'; import { styledEngineMockup } from '@pigment-css/react/internal'; - import { handleUrlReplacement, type AsyncResolver } from './utils'; type NextMeta = { @@ -284,6 +283,9 @@ export const plugin = createUnplugin((options) => { } let { cssText } = result; + + const slug = slugify(cssText); + if (isNext && !outputCss) { return { code: result.code, @@ -298,6 +300,19 @@ export const plugin = createUnplugin((options) => { if (cssText && cssText.includes('url(')) { cssText = await handleUrlReplacement(cssText, id, asyncResolve, projectPath); } + + // Valid names must start with a underscore or letter. + const layerName = `_${slug}`; + + // Fix for https://github.com/mui/pigment-css/issues/199 + // Bring each file in its own layer so that the order is maintained between css modules + // shared between layout.tsx and page.tsx. + // TODO: Do this in a way that keeps the source map correct + cssText = ` + @layer pigment.${layerName} { + ${cssText} + } + `; } if (sourceMap && result.cssSourceMapText) { @@ -324,7 +339,7 @@ export const plugin = createUnplugin((options) => { } const rootPath = process.cwd(); - const slug = slugify(cssText); + const cssFilename = path .normalize(`${id.replace(/\.[jt]sx?$/, '')}-${slug}.pigment.css`) .replace(/\\/g, path.posix.sep);