Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Underline the correct occurrence of an unsupported data type in `--value(…)` warnings ([#20554](https://github.com/tailwindlabs/tailwindcss/pull/20554))
- Keep the winning utility when collapsing candidates instead of a theme value that only matches by default ([#20540](https://github.com/tailwindlabs/tailwindcss/pull/20540))
- Canonicalization: don't collapse utilities into a utility that uses another theme variable with the same default value (e.g. `mt-card mb-card` → `my-card`, not `my-4`) ([#20574](https://github.com/tailwindlabs/tailwindcss/pull/20574))
- Ensure `@tailwindcss/postcss` rewrites relative `url(…)`s of stylesheets that are inlined before it runs (e.g. `@import`s in Vite) in optimized builds ([#20576](https://github.com/tailwindlabs/tailwindcss/pull/20576))

## [4.3.3] - 2026-07-16

Expand Down
84 changes: 83 additions & 1 deletion integrations/postcss/url-rewriting.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { css, js, json, test } from '../utils'
import { css, html, js, json, test, txt } from '../utils'

test(
'can rewrite urls in production builds',
Expand Down Expand Up @@ -147,3 +147,85 @@ test(
`)
},
)

test(
'can rewrite urls of stylesheets that Vite inlines in production builds',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"tailwindcss": "workspace:^",
"@tailwindcss/postcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'postcss.config.js': js`
export default {
plugins: {
'@tailwindcss/postcss': {},
},
}
`,
'vite.config.js': js`
import { defineConfig } from 'vite'

export default defineConfig({
build: {
assetsInlineLimit: 0,
cssMinify: false,
},
})
`,
'index.html': html`
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body></body>
</html>
`,
// Vite inlines these `@import`s before `@tailwindcss/postcss` runs
'src/index.css': css`
@import 'tailwindcss';
@import '../vendor/example-font/fonts.css';
@import './fonts/local.css';
`,
'src/fonts/local.css': css`
@font-face {
font-family: 'Local Sans';
src: url('./local-sans.woff2') format('woff2');
}
`,
'src/fonts/local-sans.woff2': txt`local-sans`,
'vendor/example-font/fonts.css': css`
@font-face {
font-family: 'Example Sans';
src: url('./fonts/example-sans.woff2') format('woff2');
}
`,
'vendor/example-font/fonts/example-sans.woff2': txt`example-sans`,
},
},
async ({ fs, exec, expect }) => {
// Vitest sets `NODE_ENV` to `test`, and `vite build` keeps a `NODE_ENV`
// that is already set
await exec('pnpm vite build', { env: { NODE_ENV: 'production' } })

let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)

let fonts = await fs.glob('dist/**/*.woff2')
expect(fonts).toHaveLength(2)

await fs.expectFileToContain(files[0][0], [
/url\("?\/assets\/example-sans-[^)]*\.woff2"?\)/,
/url\("?\/assets\/local-sans-[^)]*\.woff2"?\)/,
])
},
)
1 change: 1 addition & 0 deletions packages/@tailwindcss-node/src/index.cts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './instrumentation'
export * from './normalize-path'
export * from './optimize'
export * from './source-maps'
export { rewriteUrlsInAst } from './urls'
export { env }

// In Bun, ESM modules will also populate `require.cache`, so the module hook is
Expand Down
1 change: 1 addition & 0 deletions packages/@tailwindcss-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './instrumentation'
export * from './normalize-path'
export * from './optimize'
export * from './source-maps'
export { rewriteUrlsInAst } from './urls'
export { env }

// In Bun, ESM modules will also populate `require.cache`, so the module hook is
Expand Down
56 changes: 38 additions & 18 deletions packages/@tailwindcss-node/src/urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Minor modifications have been made to work with the Tailwind CSS codebase

import * as path from 'node:path'
import { toCss } from '../../tailwindcss/src/ast'
import { toCss, type AstNode, type Declaration } from '../../tailwindcss/src/ast'
import { parse } from '../../tailwindcss/src/css-parser'
import { walk } from '../../tailwindcss/src/walk'
import { normalizePath } from './normalize-path'
Expand Down Expand Up @@ -49,23 +49,26 @@ export async function rewriteUrls({

let ast = parse(css)

let promises: Promise<void>[] = []

function replacerForDeclaration(url: string) {
if (url[0] === '/') return url

let absoluteUrl = path.posix.join(normalizePath(base), url)
let relativeUrl = path.posix.relative(normalizePath(root), absoluteUrl)
await rewriteUrlsInAst({ ast, base: () => base, root })

// If the path points to a file in the same directory, `path.relative` will
// remove the leading `./` and we need to add it back in order to still
// consider the path relative
if (!relativeUrl.startsWith('.')) {
relativeUrl = './' + relativeUrl
}
return toCss(ast)
}

return relativeUrl
}
/**
* Rewrites the URLs of each declaration in the AST from being relative to the
* folder `base` returns for it to being relative to `root`. Declarations for
* which `base` returns `null` are left as-is.
*/
export async function rewriteUrlsInAst({
ast,
base,
root,
}: {
ast: AstNode[]
base: (node: Declaration) => string | null
root: string
}) {
let promises: Promise<void>[] = []

walk(ast, (node) => {
if (node.kind !== 'declaration') return
Expand All @@ -75,10 +78,13 @@ export async function rewriteUrls({
let isCssImageSet = cssImageSetRE.test(node.value)

if (isCssUrl || isCssImageSet) {
let declarationBase = base(node)
if (declarationBase === null) return

let rewriterToUse = isCssImageSet ? rewriteCssImageSet : rewriteCssUrls

promises.push(
rewriterToUse(node.value, replacerForDeclaration).then((url) => {
rewriterToUse(node.value, (url) => rebaseUrl(url, declarationBase, root)).then((url) => {
node.value = url
}),
)
Expand All @@ -88,8 +94,22 @@ export async function rewriteUrls({
if (promises.length) {
await Promise.all(promises)
}
}

function rebaseUrl(url: string, base: string, root: string) {
if (url[0] === '/') return url

let absoluteUrl = path.posix.join(normalizePath(base), url)
let relativeUrl = path.posix.relative(normalizePath(root), absoluteUrl)

// If the path points to a file in the same directory, `path.relative` will
// remove the leading `./` and we need to add it back in order to still
// consider the path relative
if (!relativeUrl.startsWith('.')) {
relativeUrl = './' + relativeUrl
}

return toCss(ast)
return relativeUrl
}

function rewriteCssUrls(css: string, replacer: CssUrlReplacer): Promise<string> {
Expand Down
116 changes: 114 additions & 2 deletions packages/@tailwindcss-postcss/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import dedent from 'dedent'
import { mkdir, mkdtemp, readFile, rm, unlink, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, realpath, rm, unlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'path'
import postcss from 'postcss'
import atImport from 'postcss-import'
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { pretty } from '../../tailwindcss/src/test-utils/run'
import tailwindcss from './index'
import tailwindcss, { type PluginOptions } from './index'

// We give this file path to PostCSS for processing.
// This file doesn't exist, but the path is used to resolve imports.
Expand Down Expand Up @@ -516,3 +517,114 @@ test('does not register the input file as a dependency, even if it is passed in
plugin: expect.any(String),
})
})

// Tools like Vite run `postcss-import` before our plugin, so `@import`-ed files
// are already inlined when we see them. Their `url(…)`s are still relative to
// their own file, which those tools read from the `source` of each node.
describe('stylesheets inlined before our plugin runs', () => {
let dir: string
beforeEach(async () => {
// Resolved files are real paths, so the temporary folder must be one too
dir = await realpath(await mkdtemp(path.join(tmpdir(), 'tw-postcss')))
await mkdir(path.join(dir, 'src/fonts'), { recursive: true })
await mkdir(path.join(dir, 'node_modules/example-font'), { recursive: true })
await writeFile(
path.join(dir, 'src/index.css'),
css`
@import './fonts/local.css';
@import 'example-font/fonts.css';
@tailwind utilities;
.hero {
background-image: url('./hero.png');
}
`,
)
await writeFile(
path.join(dir, 'src/fonts/local.css'),
css`
@font-face {
font-family: 'Local Sans';
src: url('./local.woff2') format('woff2');
}
`,
)
await writeFile(
path.join(dir, 'node_modules/example-font/fonts.css'),
css`
@font-face {
font-family: 'Example Sans';
src: url('./fonts/ExampleSans.woff2') format('woff2');
}
`,
)
})
afterEach(() => rm(dir, { recursive: true, force: true }))

// `postcss-import` inlines `example-font/fonts.css`, and our plugin inlines
// `./fonts/local.css` itself.
async function build(options: PluginOptions) {
let from = path.join(dir, 'src/index.css')
let processor = postcss([
atImport({ filter: (id: string) => id !== './fonts/local.css' }),
tailwindcss({ base: dir, ...options }),
])
return processor.process(await readFile(from, 'utf8'), { from })
}

test('rewrites their `url(…)`s to be relative to the input file when optimizing', async () => {
let result = await build({ optimize: { minify: false } })

expect(pretty(result.css)).toMatchInlineSnapshot(`
"
@font-face {
font-family: Local Sans;
src: url("./fonts/local.woff2") format("woff2");
}

@font-face {
font-family: Example Sans;
src: url("../node_modules/example-font/fonts/ExampleSans.woff2") format("woff2");
}

.hero {
background-image: url("./hero.png");
}
"
`)
})

test('keeps their `url(…)`s and sources when not optimizing', async () => {
let result = await build({ optimize: false })

let decls: string[] = []
result.root.walkDecls('src', (decl) => {
decls.push(`${path.relative(dir, decl.source!.input.file!)}: ${decl.value}`)
})

expect(decls).toContain(
`${path.join('node_modules', 'example-font', 'fonts.css')}: url('./fonts/ExampleSans.woff2') format('woff2')`,
)
})

test('keeps their `url(…)`s when `transformAssetUrls` is disabled', async () => {
let result = await build({ optimize: { minify: false }, transformAssetUrls: false })

expect(pretty(result.css)).toMatchInlineSnapshot(`
"
@font-face {
font-family: Local Sans;
src: url("./local.woff2") format("woff2");
}

@font-face {
font-family: Example Sans;
src: url("./fonts/ExampleSans.woff2") format("woff2");
}

.hero {
background-image: url("./hero.png");
}
"
`)
})
})
27 changes: 26 additions & 1 deletion packages/@tailwindcss-postcss/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Instrumentation,
optimize as optimizeCss,
Polyfills,
rewriteUrlsInAst,
} from '@tailwindcss/node'
import { clearRequireCache } from '@tailwindcss/node/require-cache'
import { Scanner } from '@tailwindcss/oxide'
Expand All @@ -31,7 +32,7 @@ interface CacheEntry {
const cache = new QuickLRU<string, CacheEntry>({ maxSize: 50 })

function getContextFromCache(postcss: Postcss, inputFile: string, opts: PluginOptions): CacheEntry {
let key = `${inputFile}:${opts.base ?? ''}:${JSON.stringify(opts.optimize)}`
let key = `${inputFile}:${opts.base ?? ''}:${JSON.stringify(opts.optimize)}:${opts.transformAssetUrls ?? true}`
if (cache.has(key)) return cache.get(key)!
let entry = {
mtimes: new Map<string, number>(),
Expand Down Expand Up @@ -135,6 +136,30 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
let ast = postCssAstToCssAst(root)
DEBUG && I.end('PostCSS AST -> Tailwind CSS AST')

// Plugins like `postcss-import` (which Vite adds) can inline other
// stylesheets before we run. Their URLs are still relative to
// their own file, which tools like Vite read from the `source` of
// each node. The optimized output loses that, so we make these URLs
// relative to the input file instead, like we do for stylesheets we
// inline ourselves.
let rootFile = root.source?.input.file
if (optimize && shouldRewriteUrls && rootFile) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include transformAssetUrls in the compiler cache key.

If two processors handle the same unchanged file with the same optimize setting but different transformAssetUrls settings, getContextFromCache returns the same entry. The second processor can reuse the first processor’s compiler and optimized CSS. As a result, URLs can remain rewritten when rewriting is disabled, or remain unresolved when it is enabled. Add the effective transformAssetUrls value to the cache key at Line 35.

DEBUG && I.start('Rewrite URLs of inlined stylesheets')
await rewriteUrlsInAst({
ast,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
base(node) {
let file = node.src?.[0].file

// PostCSS uses ids like `<input css 1>` for CSS without a file
if (!file || file === rootFile || !path.isAbsolute(file)) return null

return path.dirname(file)
},
root: inputBasePath,
})
DEBUG && I.end('Rewrite URLs of inlined stylesheets')
}

DEBUG && I.start('Create compiler')
let compiler = await compileAst(ast, {
from: result.opts.from,
Expand Down