Skip to content
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

CSS codemod: Add prefix(…) to necessary CSS imports when a prefix is used. #14519

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import dedent from 'dedent'
import postcss from 'postcss'
import { expect, it } from 'vitest'
import type { DesignSystem } from '../../../tailwindcss/src/design-system'
import { __unstable__loadDesignSystem } from '../../../tailwindcss/src/index'
import { formatNodes } from './format-nodes'
import { migratePrefixConfigOption } from './migrate-prefix-config-option'

const css = dedent

function migrate(input: string, designSystem?: DesignSystem) {
return postcss()
.use(migratePrefixConfigOption(designSystem))
.use(formatNodes())
.process(input, { from: expect.getState().testPath })
.then((result) => result.css)
}

it('Does not add prefix when not configured`', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@config "config.js";
`,
{
base: __dirname,
loadModule: async (id, base) => ({ base, module: {} }),
},
)

expect(
await migrate(
css`
@import 'tailwindcss';
@import 'tailwindcss/theme';
`,
designSystem,
),
).toMatchInlineSnapshot(`
"@import 'tailwindcss';
@import 'tailwindcss/theme';"
`)
})

it('Adds prefix to imports', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@config "config.js";
`,
{
base: __dirname,
loadModule: async (id, base) => ({ base, module: { prefix: 'tw' } }),
},
)

expect(
await migrate(
css`
@import 'tailwindcss';
@import 'tailwindcss' layer(tailwind);
@import 'tailwindcss/theme';
@import 'tailwindcss/theme' layer(theme);
`,
designSystem,
),
).toMatchInlineSnapshot(`
"@import 'tailwindcss' prefix(tw);
@import 'tailwindcss' layer(tailwind) prefix(tw);
@import 'tailwindcss/theme' prefix(tw);
@import 'tailwindcss/theme' layer(theme) prefix(tw);"
`)
})

it('Does not add prefix if it is already there', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@config "config.js";
`,
{
base: __dirname,
loadModule: async (id, base) => ({ base, module: { prefix: 'tw' } }),
},
)

expect(
await migrate(
css`
@import 'tailwindcss' prefix(wat);
@import 'tailwindcss/theme' prefix(wat);
`,
designSystem,
),
).toMatchInlineSnapshot(`
"@import 'tailwindcss' prefix(wat);
@import 'tailwindcss/theme' prefix(wat);"
`)
})

it('Migrates a prefix ending with a dash', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@config "config.js";
`,
{
base: __dirname,
loadModule: async (id, base) => ({ base, module: { prefix: 'tw-' } }),
},
)

expect(
await migrate(
css`
@import 'tailwindcss';
@import 'tailwindcss/theme';
`,
designSystem,
),
).toMatchInlineSnapshot(`
"@import 'tailwindcss' prefix(tw);
@import 'tailwindcss/theme' prefix(tw);"
`)
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { type Plugin, type Root } from 'postcss'
import type { DesignSystem } from '../../../tailwindcss/src/design-system'

export function migratePrefixConfigOption(designSystem?: DesignSystem): Plugin {
let prefix = designSystem?.theme.prefix

// @import "tailwindcss"
// @import "tailwindcss/theme"
let IS_TAILWIND_IMPORT = /^["']tailwindcss(\/theme)?["']/
let HAS_PREFIX = /prefix([^)]+)/

function migrate(root: Root) {
// If there's no prefix configured, we don't need to do anything
if (typeof prefix !== 'string') return

root.walkAtRules((node) => {
if (node.name !== 'import') return
if (!node.params.match(IS_TAILWIND_IMPORT)) return
if (node.params.match(HAS_PREFIX)) return

node.params += ` prefix(${prefix})`
})
}

// TODO: We should remove `prefix: "…"` from the config file
// - if its on its own line just remove the line
// - if not then just remove the `prefix: "…"` part
// - do we need to use a JS AST thing for this?
//
// The prefix might be in a preset or a plugin so if we don't find it
// we should just log a warning and let the user handle it themselves

return {
postcssPlugin: '@tailwindcss/upgrade/migrate-prefix-config-option',
OnceExit: migrate,
}
}
4 changes: 3 additions & 1 deletion packages/@tailwindcss-upgrade/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ async function run() {
files = files.filter((file) => file.endsWith('.css'))

// Migrate each file
await Promise.allSettled(files.map((file) => migrateStylesheet(file)))
await Promise.allSettled(
files.map((file) => migrateStylesheet(file, parsedConfig?.designSystem)),
)

success('Stylesheet migration complete.')
}
Expand Down
13 changes: 10 additions & 3 deletions packages/@tailwindcss-upgrade/src/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import postcss from 'postcss'
import type { DesignSystem } from '../../tailwindcss/src/design-system'
import { formatNodes } from './codemods/format-nodes'
import { migrateAtApply } from './codemods/migrate-at-apply'
import { migrateAtLayerUtilities } from './codemods/migrate-at-layer-utilities'
import { migrateMissingLayers } from './codemods/migrate-missing-layers'
import { migratePrefixConfigOption } from './codemods/migrate-prefix-config-option'
import { migrateTailwindDirectives } from './codemods/migrate-tailwind-directives'

export async function migrateContents(contents: string, file?: string) {
export async function migrateContents(
contents: string,
file?: string,
designSystem?: DesignSystem,
) {
return postcss()
.use(migrateAtApply())
.use(migrateAtLayerUtilities())
.use(migrateMissingLayers())
.use(migrateTailwindDirectives())
.use(migratePrefixConfigOption(designSystem))
.use(formatNodes())
.process(contents, { from: file })
.then((result) => result.css)
}

export async function migrate(file: string) {
export async function migrate(file: string, designSystem?: DesignSystem) {
let fullPath = path.resolve(process.cwd(), file)
let contents = await fs.readFile(fullPath, 'utf-8')

await fs.writeFile(fullPath, await migrateContents(contents, fullPath))
await fs.writeFile(fullPath, await migrateContents(contents, fullPath, designSystem))
}