Skip to content

Ensure @tailwindcss/upgrade runs on Tailwind CSS v4 projects and is idempotent #17717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 36 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
e326b54
add semver dependency
RobinMalfait Mar 31, 2025
83bf845
do not require Tailwind CSS v3 projects anymore
RobinMalfait Apr 1, 2025
2879f4e
add `version` related helpers
RobinMalfait Apr 18, 2025
ba315ec
conditionally apply migrations based on version number
RobinMalfait Apr 18, 2025
0f97d3e
only link stylesheets to JS config files when migrating Tailwind CSS …
RobinMalfait Apr 18, 2025
6bef56e
only split stylesheets when migrating Tailwind CSS v3 projects
RobinMalfait Apr 18, 2025
986092a
only migrate PostCSS config when migrating Tailwind CSS v3 projects
RobinMalfait Apr 18, 2025
cfaeb55
only migrate JS files if they have linked config paths
RobinMalfait Apr 18, 2025
2f6e368
make `jsConfigMigration` nullable
RobinMalfait Apr 18, 2025
f78f582
change order
RobinMalfait Apr 18, 2025
b6089e4
bail on empty config
RobinMalfait Apr 18, 2025
a2836e5
make `UserConfig` nullable
RobinMalfait Apr 18, 2025
c52201f
migrate source files based on Tailwind root stylesheets
RobinMalfait Apr 18, 2025
eacaabf
remove unused `hoistStaticGlobParts`
RobinMalfait Apr 18, 2025
9be7647
make `configFilePath` also nullable
RobinMalfait Apr 18, 2025
bc93e2c
do not migrate `preflight` in non-v3 projects
RobinMalfait Apr 18, 2025
51b2200
run prettier
RobinMalfait Apr 18, 2025
6a492da
upgrade `tailwindcss` after we migrated the stylesheets
RobinMalfait Apr 18, 2025
c5ec584
remove test that requires Tailwind CSS v3
RobinMalfait Apr 18, 2025
71f3461
make the `DesignSystem` fully nullable
RobinMalfait Apr 18, 2025
6ffa7cb
mock version in local tests
RobinMalfait Apr 18, 2025
4f987fa
only migrate `@layer` in v3 projects
RobinMalfait Apr 18, 2025
1b53461
add migrations for newly deprecated classes
RobinMalfait Apr 18, 2025
6085b47
add `:user-valid` and `:user-invalid` arbitrary variant replacements
RobinMalfait Apr 18, 2025
a6d4309
replace arbitrary `@media` variants
RobinMalfait Apr 18, 2025
5857fd0
handle `[@media_not(…)]` variants
RobinMalfait Apr 18, 2025
ba4cab7
handle `@media` with single argument (e.g.: `@media print`)
RobinMalfait Apr 18, 2025
0e61002
ensure we re-print the candidate in case it didn't change
RobinMalfait Apr 18, 2025
37323c6
add tests to ensure upgrade tool runs on v4 and is idempotent
RobinMalfait Apr 18, 2025
aadc926
add test to ensure upgrade runs on v4 projects
RobinMalfait Apr 18, 2025
d20902f
only commit changes in dirty git repo
RobinMalfait Apr 19, 2025
94ef122
Merge branch 'main' into feat/enable-codemods-on-v4-projects
RobinMalfait Apr 22, 2025
7bbeb99
Merge branch 'main' into feat/enable-codemods-on-v4-projects
RobinMalfait Apr 22, 2025
3d8eed9
adjust comment
RobinMalfait Apr 22, 2025
fff3cc0
update changelog
RobinMalfait Apr 22, 2025
6b5935c
add new migration examples to upgrade test
RobinMalfait Apr 22, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Ensure `@tailwindcss/upgrade` runs on Tailwind CSS v4 projects ([#17717](https://github.com/tailwindlabs/tailwindcss/pull/17717))

### Fixed

- Don't scan `.geojson` files for classes by default ([#17700](https://github.com/tailwindlabs/tailwindcss/pull/17700))
Expand Down
220 changes: 186 additions & 34 deletions integrations/upgrade/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isRepoDirty } from '../../packages/@tailwindcss-upgrade/src/utils/git'
import { candidate, css, html, js, json, test, ts } from '../utils'

test(
Expand Down Expand Up @@ -2595,40 +2596,6 @@ test(
},
)

test(
'requires Tailwind v3 before attempting an upgrade',
{
fs: {
'package.json': json`
{
"dependencies": {
"tailwindcss": "workspace:^",
"@tailwindcss/upgrade": "workspace:^"
}
}
`,
'tailwind.config.ts': js` export default {} `,
'src/index.html': html`
<div class="underline"></div>
`,
'src/index.css': css`
@tailwind base;
@tailwind components;
@tailwind utilities;
`,
},
},
async ({ exec, expect }) => {
let output = await exec('npx @tailwindcss/upgrade', {}, { ignoreStdErr: true }).catch((e) =>
e.toString(),
)

expect(output).toMatch(
/Tailwind CSS v.* found. The migration tool can only be run on v3 projects./,
)
},
)

test(
`upgrades opacity namespace values to percentages`,
{
Expand Down Expand Up @@ -2810,6 +2777,191 @@ test(
},
)

test(
'upgrades are idempotent, and can run on v4 projects',
{
fs: {
'package.json': json`
{
"dependencies": {
"tailwindcss": "^3",
"@tailwindcss/upgrade": "workspace:^"
},
"devDependencies": {
"@tailwindcss/cli": "workspace:^"
}
}
`,
'tailwind.config.js': js`
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{html,js}'],
}
`,
'src/index.html': html`
<div class="ring"></div>
`,
'src/input.css': css`
@tailwind base;
@tailwind components;
@tailwind utilities;

.foo {
@apply !bg-[var(--my-color)] rounded;
}
`,
},
},
async ({ exec, fs, expect }) => {
await exec('npx @tailwindcss/upgrade')

let before = await fs.dumpFiles('./src/**/*.{css,html}')
expect(before).toMatchInlineSnapshot(`
"
--- ./src/index.html ---
<div class="ring-3"></div>

--- ./src/input.css ---
@import 'tailwindcss';

/*
The default border color has changed to \`currentcolor\` in Tailwind CSS v4,
so we've added these compatibility styles to make sure everything still
looks the same as it did with Tailwind CSS v3.

If we ever want to remove these styles, we need to add an explicit border
color utility to any element that depends on these defaults.
*/
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentcolor);
}
}

.foo {
@apply bg-(--my-color)! rounded-sm;
}
"
`)

// Commit the changes
if (isRepoDirty()) {
await exec('git add .')
await exec('git commit -m "upgrade"')
}

// Run the upgrade again
let output = await exec('npx @tailwindcss/upgrade')
expect(output).toContain('No changes were made to your repository')

let after = await fs.dumpFiles('./src/**/*.{css,html}')
expect(after).toMatchInlineSnapshot(`
"
--- ./src/index.html ---
<div class="ring-3"></div>

--- ./src/input.css ---
@import 'tailwindcss';

/*
The default border color has changed to \`currentcolor\` in Tailwind CSS v4,
so we've added these compatibility styles to make sure everything still
looks the same as it did with Tailwind CSS v3.

If we ever want to remove these styles, we need to add an explicit border
color utility to any element that depends on these defaults.
*/
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentcolor);
}
}

.foo {
@apply bg-(--my-color)! rounded-sm;
}
"
`)

// Ensure the file system is in the same state
expect(before).toEqual(after)
},
)

test(
'upgrades run on v4 projects',
{
fs: {
'package.json': json`
{
"dependencies": {
"tailwindcss": "^4",
"@tailwindcss/upgrade": "workspace:^"
},
"devDependencies": {
"@tailwindcss/cli": "workspace:^"
}
}
`,
'src/index.html': html`
<!-- Migrating 'ring', 'rounded' and 'outline-none' are unsafe in v4 -> v4 migrations -->
<div class="ring rounded outline"></div>

<!-- Variant order is also unsafe to change in v4 projects -->
<div class="file:hover:flex *:hover:flex"></div>
<div class="hover:file:flex hover:*:flex"></div>

<!-- These are safe to migrate: -->
<div
class="!flex bg-red-500/[var(--my-opacity)] [@media(pointer:fine)]:flex bg-right-bottom object-left-top"
></div>
`,
'src/input.css': css`
@import 'tailwindcss';

.foo {
@apply !bg-[var(--my-color)];
}
`,
},
},
async ({ exec, fs, expect }) => {
await exec('npx @tailwindcss/upgrade')

expect(await fs.dumpFiles('./src/**/*.{css,html}')).toMatchInlineSnapshot(`
"
--- ./src/index.html ---
<!-- Migrating 'ring', 'rounded' and 'outline-none' are unsafe in v4 -> v4 migrations -->
<div class="ring rounded outline"></div>

<!-- Variant order is also unsafe to change in v4 projects -->
<div class="file:hover:flex *:hover:flex"></div>
<div class="hover:file:flex hover:*:flex"></div>

<!-- These are safe to migrate: -->
<div
class="flex! bg-red-500/(--my-opacity) pointer-fine:flex bg-bottom-right object-top-left"
></div>

--- ./src/input.css ---
@import 'tailwindcss';

.foo {
@apply bg-(--my-color)!;
}
"
`)
},
)

function withBOM(text: string): string {
return '\uFEFF' + text
}
8 changes: 5 additions & 3 deletions packages/@tailwindcss-upgrade/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@
"postcss-import": "^16.1.0",
"postcss-selector-parser": "^7.1.0",
"prettier": "catalog:",
"semver": "^7.7.1",
"tailwindcss": "workspace:*",
"tree-sitter": "^0.22.4",
"tree-sitter-typescript": "^0.23.2",
"tailwindcss": "workspace:*"
"tree-sitter-typescript": "^0.23.2"
},
"devDependencies": {
"@types/braces": "^3.0.5",
"@types/node": "catalog:",
"@types/postcss-import": "^14.0.3"
"@types/postcss-import": "^14.0.3",
"@types/semver": "^7.7.0"
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { __unstable__loadDesignSystem } from '@tailwindcss/node'
import dedent from 'dedent'
import postcss from 'postcss'
import { expect, it } from 'vitest'
import { expect, it, vi } from 'vitest'
import type { Config } from '../../../../tailwindcss/src/compat/plugin-api'
import * as versions from '../../utils/version'
import { migrateAtApply } from './migrate-at-apply'
vi.spyOn(versions, 'isMajor').mockReturnValue(true)

const css = dedent

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ export function migrateAtApply({
designSystem,
userConfig,
}: {
designSystem: DesignSystem
userConfig: Config
designSystem: DesignSystem | null
userConfig: Config | null
}): Plugin {
function migrate(atRule: AtRule) {
let utilities = atRule.params.split(/(\s+)/)
Expand All @@ -35,6 +35,8 @@ export function migrateAtApply({
})

return async () => {
if (!designSystem) return

// If we have a valid designSystem and config setup, we can run all
// candidate migrations on each utility
params = await Promise.all(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import dedent from 'dedent'
import postcss from 'postcss'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { Stylesheet } from '../../stylesheet'
import * as versions from '../../utils/version'
import { formatNodes } from './format-nodes'
import { migrateAtLayerUtilities } from './migrate-at-layer-utilities'
import { sortBuckets } from './sort-buckets'
vi.spyOn(versions, 'isMajor').mockReturnValue(true)

const css = dedent

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ import { type AtRule, type Comment, type Plugin, type Rule } from 'postcss'
import SelectorParser from 'postcss-selector-parser'
import { segment } from '../../../../tailwindcss/src/utils/segment'
import { Stylesheet } from '../../stylesheet'
import * as version from '../../utils/version'
import { walk, WalkAction, walkDepth } from '../../utils/walk'

export function migrateAtLayerUtilities(stylesheet: Stylesheet): Plugin {
function migrate(atRule: AtRule) {
// Migrating `@layer utilities` to `@utility` is only supported in Tailwind
// CSS v3 projects. Tailwind CSS v4 projects could also have `@layer
// utilities` but those aren't actual utilities.
if (!version.isMajor(3)) return

// Only migrate `@layer utilities` and `@layer components`.
if (atRule.params !== 'utilities' && atRule.params !== 'components') return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ export function migrateConfig(
{
configFilePath,
jsConfigMigration,
}: { configFilePath: string; jsConfigMigration: JSConfigMigration },
}: { configFilePath: string | null; jsConfigMigration: JSConfigMigration | null },
): Plugin {
function migrate() {
if (!sheet.isTailwindRoot) return
if (!configFilePath) return

let alreadyInjected = ALREADY_INJECTED.get(sheet)
if (alreadyInjected && alreadyInjected.includes(configFilePath)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export function migrateMediaScreen({
designSystem,
userConfig,
}: {
designSystem?: DesignSystem
userConfig?: Config
designSystem?: DesignSystem | null
userConfig?: Config | null
} = {}): Plugin {
function migrate(root: Root) {
if (!designSystem || !userConfig) return
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { __unstable__loadDesignSystem } from '@tailwindcss/node'
import dedent from 'dedent'
import postcss from 'postcss'
import { expect, it } from 'vitest'
import { expect, it, vi } from 'vitest'
import * as versions from '../../utils/version'
import { formatNodes } from './format-nodes'
import { migratePreflight } from './migrate-preflight'
import { sortBuckets } from './sort-buckets'
vi.spyOn(versions, 'isMajor').mockReturnValue(true)

const css = dedent

Expand Down
Loading