tailwindcss/integrations/postcss/multi-root.test.ts
Philipp Spiess b38948337d
Make @reference emit variable fallbacks instead of CSS variable declarations (#16774)
Fixes #16725

When using `@reference "tailwindcss";` inside a separate CSS root (e.g.
Svelte `<style>` components, CSS modules, etc.), we have no guarantee
that the CSS variables will be defined in the main stylesheet (or if
there even is one). To work around potential issues with this we decided
in #16676 that we would emit all used CSS variables from the `@theme`
inside the `@reference` block.

However, this is not only a bit surprising but also unexpected in CSS
modules and Next.js that **requires CSS module files to only create
scope-able declarations**. To fix this issue, we decided to not emit CSS
variables but instead ensure all `var(…)` calls we create for theme
values in reference mode will simply have their fallback value added.

This ensures styles work as-expected even if the root Tailwind file does
not pick up the variable as being used or _if you don't add a root at
all_. Furthermore we do not duplicate any variable declarations across
your stylesheets and you still have the ability to change variables at
runtime.

## Test plan

- Updated snapshots everywhere (see diff)
- New Next.js CSS modules integration test
2025-02-25 11:36:43 +01:00

51 lines
1.4 KiB
TypeScript

import { candidate, css, html, js, json, test } from '../utils'
test(
'production build',
{
fs: {
'package.json': json`
{
"dependencies": {
"postcss": "^8",
"postcss-cli": "^10",
"tailwindcss": "workspace:^",
"@tailwindcss/postcss": "workspace:^"
}
}
`,
'postcss.config.js': js`
module.exports = {
plugins: {
'@tailwindcss/postcss': {},
},
}
`,
'index.html': html`
<div class="one:underline two:underline"></div>
`,
'src/shared.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/root1.css': css`
@import './shared.css';
@custom-variant one (&:is([data-root='1']));
`,
'src/root2.css': css`
@import './shared.css';
@custom-variant two (&:is([data-root='2']));
`,
},
},
async ({ fs, exec }) => {
await exec('pnpm postcss src/*.css -d dist')
await fs.expectFileToContain('dist/root1.css', [candidate`one:underline`])
await fs.expectFileNotToContain('dist/root1.css', [candidate`two:underline`])
await fs.expectFileNotToContain('dist/root2.css', [candidate`one:underline`])
await fs.expectFileToContain('dist/root2.css', [candidate`two:underline`])
},
)