Always add layer(…) as the first param to @import (#15102)

This PR ensures that when we inject `layer(…)` into an `@import` that it
always gets inserted as the first param. The `layer(…)` has to come
first by spec.

Input:
```css
@import "./foo" supports(--foo);
```

Before:
```css
@import "./foo" supports(--foo) layer(utilities);
```

After:
```css
@import "./foo" layer(utilities) supports(--foo);
```
This commit is contained in:
Robin Malfait 2024-11-22 15:09:26 +01:00 committed by GitHub
parent dad9ac6209
commit dd2058df6a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 21 additions and 1 deletions

View File

@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Use configured `--letter-spacing` values for custom font size utilities ([#15099](https://github.com/tailwindlabs/tailwindcss/pull/15099))
- Ensure `space-x/y-*` and `divide-x/y-*` with variants can undo `space-x/y-reverse` and `divide-x/y-reverse` ([#15094](https://github.com/tailwindlabs/tailwindcss/pull/15094))
- _Upgrade (experimental)_: Always add `layer(…)` as the first param to `@import` ([#15102](https://github.com/tailwindlabs/tailwindcss/pull/15102))
### Changed

View File

@ -40,6 +40,22 @@ it('should add missing `layer(…)` to imported files', async () => {
`)
})
it('should add missing `layer(…)` as the first param after the import itself', async () => {
expect(
await migrate(css`
@import 'tailwindcss/utilities' supports(--foo); /* Expected no layer */
@import './foo.css' supports(--foo); /* Expected layer(utilities) supports(--foo) */
@import './bar.css' supports(--foo); /* Expected layer(utilities) supports(--foo) */
@import 'tailwindcss/components' supports(--foo); /* Expected no layer */
`),
).toMatchInlineSnapshot(`
"@import 'tailwindcss/utilities' supports(--foo); /* Expected no layer */
@import './foo.css' layer(utilities) supports(--foo); /* Expected layer(utilities) supports(--foo) */
@import './bar.css' layer(utilities) supports(--foo); /* Expected layer(utilities) supports(--foo) */
@import 'tailwindcss/components' supports(--foo); /* Expected no layer */"
`)
})
it('should not migrate anything if no `@tailwind` directives (or imports) are found', async () => {
expect(
await migrate(css`

View File

@ -1,4 +1,5 @@
import { AtRule, type ChildNode, type Plugin, type Root } from 'postcss'
import { segment } from '../../../tailwindcss/src/utils/segment'
export function migrateMissingLayers(): Plugin {
function migrate(root: Root) {
@ -119,7 +120,9 @@ export function migrateMissingLayers(): Plugin {
if (node.type !== 'atrule' || node.name !== 'import') continue
if (!node.params.includes('layer(')) {
node.params += ` layer(${targetLayerName})`
let params = segment(node.params, ' ')
params.splice(1, 0, `layer(${targetLayerName})`)
node.params = params.join(' ')
node.raws.tailwind_injected_layer = true
}
}