tailwindcss/integrations/vite/resolvers.test.ts
Robin Malfait 5a799900d4
Always resolve relative files, relative to the current .css file (#19965)
This PR fixes an issue where resolving of certain CSS or JS files
results in the wrong paths. The issue happens if you have a setup where
a relative file path _also_ exists in the parent folder:

```css
/* src/foo.css */
.foo-in-root {}

/* src/theme/a.css */
@import "./foo.css"; /* This resolved to the file above, instead of the file below */

/* src/theme/foo.css */
.foo-in-theme {}
```

This happened because we resolved relative to a `base` folder, but Vite
expects an `importer` instead. The difference is subtle, but they expect
a file. On that file they use `let base = path.dirname(importer)` to get
a base path out themselves.

This in turn means that if you pass in a folder, you get this:
```js
path.dirname('/path/to/my-project') // /path/to
```

If we gave it a proper file, then we get the proper base path
```js
path.dirname('/path/to/my-project/index.css') // /path/to/my-project
```

I'm actually surprised that this didn't cause issues earlier... but it
did result in error since we recently started resolving files using
Vite's `aliasOnly: true` feature such taht Vite aliases work as well.

With this change, we now make sure that:

1. We use a proper `importer` instead of the `base` path
2. We refactor the resolving logic such that we try with `aliasOnly:
true` first, then `aliasOnly: false`

We also still ensure that in the CSS resolver we expect a `.css` file,
and in the JS resolver we _don't_ expect a `.css` file (which can happen
if a `"browser": "./dist/index.css"` field in package.json points to a
CSS file, daisyUI does this for example).

Fixes: #19956

## Test plan

1. Added additional (failing) integration tests to reproduce the linked
issue
2. Existing integration tests pass

While the build still worked, the linked issue resulted in a much bigger
file size because the wrong .css files were included. With this fix, the
number is correct again:
<img width="1234" height="1037" alt="image"
src="https://github.com/user-attachments/assets/fdff803c-0db2-4066-92fa-064c2816b35c"
/>

Since this is touching code related to previous PRs, I wanted to
manually make sure that these still work as expected:

- https://github.com/tailwindlabs/tailwindcss/issues/19950: This one is
about daisyUI and the `.css` file referenced in the package.json's
`"browser"` field: <img width="782" height="1229" alt="image"
src="https://github.com/user-attachments/assets/fb7b9d3b-527b-414b-94b0-2be7e96056f1"
/>

- https://github.com/tailwindlabs/tailwindcss/issues/19946: This one is
about the Vite alias being just a single `@` causing issues with
`@plugin "@tailwindcss/typography";` for example: <img width="1694"
height="1856" alt="image"
src="https://github.com/user-attachments/assets/d1935ecf-e80a-4945-a69a-ec3c5223efab"
/>


[ci-all]
2026-04-24 15:07:56 +02:00

802 lines
21 KiB
TypeScript

import { describe } from 'vitest'
import {
candidate,
css,
fetchStyles,
html,
js,
json,
retryAssertion,
test,
ts,
txt,
yaml,
} from '../utils'
test(
'resolves tsconfig paths in production build',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'tsconfig.json': json`
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
tsconfigPaths: true,
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="underline custom-underline">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import '@/styles/base.css';
@plugin '@/plugin.js';
`,
'src/styles/base.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/plugin.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.custom-underline': { 'border-bottom': '1px solid green' } })
}
`,
},
},
async ({ fs, exec, expect }) => {
await exec('pnpm vite build')
let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)
let [filename] = files[0]
await fs.expectFileToContain(filename, [candidate`underline`, candidate`custom-underline`])
},
)
test(
'resolves tsconfig paths in dev mode',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'tsconfig.json': json`
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
tsconfigPaths: true,
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="underline custom-underline">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import '@/styles/base.css';
@plugin '@/plugin.js';
`,
'src/styles/base.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/plugin.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.custom-underline': { 'border-bottom': '1px solid green' } })
}
`,
},
},
async ({ spawn, expect }) => {
let process = await spawn('pnpm vite dev')
await process.onStdout((m) => m.includes('ready in'))
let url = ''
await process.onStdout((m) => {
let match = /Local:\s*(http.*)\//.exec(m)
if (match) url = match[1]
return Boolean(url)
})
await retryAssertion(async () => {
let styles = await fetchStyles(url, '/index.html')
expect(styles).toContain(candidate`underline`)
expect(styles).toContain(candidate`custom-underline`)
})
},
)
test(
'resolves at-sign aliases in production build',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import { fileURLToPath } from 'node:url'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
alias: [{ find: '@', replacement: fileURLToPath(new URL('.', import.meta.url)) }],
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="underline custom-underline">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import '@/src/styles/base.css';
@plugin '@/src/plugin.js';
`,
'src/styles/base.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/plugin.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.custom-underline': { 'border-bottom': '1px solid green' } })
}
`,
},
},
async ({ fs, exec, expect }) => {
await exec('pnpm vite build')
let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)
let [filename] = files[0]
await fs.expectFileToContain(filename, [candidate`underline`, candidate`custom-underline`])
},
)
test(
'resolves package plugins in production build with at-sign aliases',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"tailwind-scrollbar": "^4.0.2",
"tailwindcss-motion": "^1.1.1",
"vite": "^8"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import { fileURLToPath } from 'node:url'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
alias: [{ find: '@', replacement: fileURLToPath(new URL('.', import.meta.url)) }],
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="scrollbar scrollbar-thumb-red-500 motion-preset-fade">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import 'tailwindcss';
@plugin 'tailwind-scrollbar';
@plugin 'tailwindcss-motion';
`,
},
},
async ({ fs, exec, expect }) => {
await exec('pnpm vite build')
let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)
let [filename] = files[0]
await fs.expectFileToContain(filename, [
candidate`scrollbar`,
candidate`scrollbar-thumb-red-500`,
candidate`motion-preset-fade`,
])
},
)
test(
'resolves package plugins to JS entries in production build when browser points to CSS',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"plugin-browser-css": "workspace:*",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'pnpm-workspace.yaml': yaml`
#
packages:
- packages/*
`,
'packages/plugin-browser-css/package.json': json`
{
"name": "plugin-browser-css",
"version": "1.0.0",
"type": "module",
"main": "./index.js",
"module": "./index.js",
"browser": "./browser.css"
}
`,
'packages/plugin-browser-css/index.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.browser-css-plugin': { 'border-bottom': '1px solid green' } })
}
`,
'packages/plugin-browser-css/browser.css': css`
.should-not-be-loaded-as-a-plugin {
display: none;
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
})
`,
'index.html': html`
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="browser-css-plugin">Hello, world!</div>
</body>
</html>
`,
'src/index.css': css`
@import 'tailwindcss';
@plugin 'plugin-browser-css';
`,
},
},
async ({ fs, exec, expect }) => {
await exec('pnpm vite build')
let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)
let [filename] = files[0]
await fs.expectFileToContain(filename, [candidate`browser-css-plugin`])
},
)
test(
'resolves package plugins to JS entries in dev mode when browser points to CSS',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"plugin-browser-css": "workspace:*",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'pnpm-workspace.yaml': yaml`
#
packages:
- packages/*
`,
'packages/plugin-browser-css/package.json': json`
{
"name": "plugin-browser-css",
"version": "1.0.0",
"type": "module",
"main": "./index.js",
"module": "./index.js",
"browser": "./browser.css"
}
`,
'packages/plugin-browser-css/index.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.browser-css-plugin': { 'border-bottom': '1px solid green' } })
}
`,
'packages/plugin-browser-css/browser.css': css`
.should-not-be-loaded-as-a-plugin {
display: none;
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
})
`,
'index.html': html`
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="browser-css-plugin">Hello, world!</div>
</body>
</html>
`,
'src/index.css': css`
@import 'tailwindcss';
@plugin 'plugin-browser-css';
`,
},
},
async ({ spawn, expect }) => {
let process = await spawn('pnpm vite dev')
await process.onStdout((m) => m.includes('ready in'))
let url = ''
await process.onStdout((m) => {
let match = /Local:\s*(http.*)\//.exec(m)
if (match) url = match[1]
return Boolean(url)
})
await retryAssertion(async () => {
let styles = await fetchStyles(url, '/index.html')
expect(styles).toContain(candidate`browser-css-plugin`)
})
},
)
test(
'resolves package plugins in dev mode when package exports CSS files',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"daisyui": "^5",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
})
`,
'index.html': html`
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<button class="btn btn-primary">Hello, world!</button>
</body>
</html>
`,
'src/index.css': css`
@import 'tailwindcss';
@plugin 'daisyui';
`,
},
},
async ({ spawn, expect }) => {
let process = await spawn('pnpm vite dev')
await process.onStdout((m) => m.includes('ready in'))
let url = ''
await process.onStdout((m) => {
let match = /Local:\s*(http.*)\//.exec(m)
if (match) url = match[1]
return Boolean(url)
})
await retryAssertion(async () => {
let styles = await fetchStyles(url, '/index.html')
expect(styles).toContain('.btn')
expect(styles).toContain('.btn-primary')
})
},
)
test(
'resolve relative CSS files correctly',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
})
`,
'index.html': html`
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body></body>
</html>
`,
'src/index.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
@import './themes/glow.css';
`,
// References a file in the current folder, which names happens to match a
// file in the parent folder as well.
'src/themes/glow.css': css`@import './entry.css';`,
'src/themes/entry.css': css`
.do-include-me {
color: green;
}
`,
// Never rerefenced, so should not be included
'src/entry.css': css`
.do-not-include-me {
color: red;
}
`,
},
},
async ({ exec, fs, expect }) => {
await exec('pnpm vite build')
expect((await fs.dumpFiles('./dist/**/*.css')).replace(/-([a-zA-Z0-9]*?)\.css/g, '-<hash>.css'))
.toMatchInlineSnapshot(`
"
--- ./dist/assets/index-<hash>.css ---
.do-include-me {
color: green;
}
"
`)
},
)
test(
'resolve relative JS files correctly',
{
fs: {
'package.json': json`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
"vite": "^8"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
build: { cssMinify: false },
plugins: [tailwindcss()],
})
`,
'index.html': html`
<html>
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body></body>
</html>
`,
'src/index.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
@import './themes/glow.css';
`,
// References a file in the current folder, which names happens to match a
// file in the parent folder as well.
'src/themes/glow.css': css`@plugin "./my-plugin.js";`,
'src/themes/my-plugin.js': ts`
export default function ({ addBase }) {
addBase({ '.do-include-me': { color: 'green' } })
}
`,
// Never rerefenced, so should not be included
'src/my-plugin.js': css`
export default function ({ addBase }) {
addBase({ '.do-not-include-me': { 'color': 'red' } })
}
`,
},
},
async ({ exec, fs, expect }) => {
await exec('pnpm vite build')
expect((await fs.dumpFiles('./dist/**/*.css')).replace(/-([a-zA-Z0-9]*?)\.css/g, '-<hash>.css'))
.toMatchInlineSnapshot(`
"
--- ./dist/assets/index-<hash>.css ---
@layer base {
.do-include-me {
color: green;
}
}
"
`)
},
)
describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
test(
'resolves aliases in production build',
{
fs: {
'package.json': txt`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
${transformer === 'lightningcss' ? `"lightningcss": "^1",` : ''}
"vite": "^5.3.5"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import { fileURLToPath } from 'node:url'
export default defineConfig({
css: ${transformer === 'postcss' ? '{}' : "{ transformer: 'lightningcss' }"},
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
alias: {
'#css-alias': fileURLToPath(new URL('./src/alias.css', import.meta.url)),
'#js-alias': fileURLToPath(new URL('./src/plugin.js', import.meta.url)),
},
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="underline custom-underline">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import '#css-alias';
@plugin '#js-alias';
`,
'src/alias.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/plugin.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.custom-underline': { 'border-bottom': '1px solid green' } })
}
`,
},
},
async ({ fs, exec, expect }) => {
await exec('pnpm vite build')
let files = await fs.glob('dist/**/*.css')
expect(files).toHaveLength(1)
let [filename] = files[0]
await fs.expectFileToContain(filename, [candidate`underline`, candidate`custom-underline`])
},
)
test(
'resolves aliases in dev mode',
{
fs: {
'package.json': txt`
{
"type": "module",
"dependencies": {
"@tailwindcss/vite": "workspace:^",
"tailwindcss": "workspace:^"
},
"devDependencies": {
${transformer === 'lightningcss' ? `"lightningcss": "^1",` : ''}
"vite": "^5.3.5"
}
}
`,
'vite.config.ts': ts`
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import { fileURLToPath } from 'node:url'
export default defineConfig({
css: ${transformer === 'postcss' ? '{}' : "{ transformer: 'lightningcss' }"},
build: { cssMinify: false },
plugins: [tailwindcss()],
resolve: {
alias: {
'#css-alias': fileURLToPath(new URL('./src/alias.css', import.meta.url)),
'#js-alias': fileURLToPath(new URL('./src/plugin.js', import.meta.url)),
},
},
})
`,
'index.html': html`
<head>
<link rel="stylesheet" href="./src/index.css" />
</head>
<body>
<div class="underline custom-underline">Hello, world!</div>
</body>
`,
'src/index.css': css`
@import '#css-alias';
@plugin '#js-alias';
`,
'src/alias.css': css`
@reference 'tailwindcss/theme';
@import 'tailwindcss/utilities';
`,
'src/plugin.js': js`
export default function ({ addUtilities }) {
addUtilities({ '.custom-underline': { 'border-bottom': '1px solid green' } })
}
`,
},
},
async ({ spawn, expect }) => {
let process = await spawn('pnpm vite dev')
await process.onStdout((m) => m.includes('ready in'))
let url = ''
await process.onStdout((m) => {
let match = /Local:\s*(http.*)\//.exec(m)
if (match) url = match[1]
return Boolean(url)
})
await retryAssertion(async () => {
let styles = await fetchStyles(url, '/index.html')
expect(styles).toContain(candidate`underline`)
expect(styles).toContain(candidate`custom-underline`)
})
},
)
})