Handle bare CSS @import specifiers for Tailwind v4

Tailwind v4 projects typically include `@import "tailwindcss";` in
their CSS entry and often `@import` third-party CSS plugins like
`tw-animate-css`. Both cases were broken:

1. esbuild tried to resolve `tailwindcss` through the ESM CDN as JS,
   producing 'Cannot import <...> into a CSS file'. The existing
   CSS-importer guard used `new URL(args.importer)` to detect CSS
   importers, but esbuild passes fs-namespace importers as plain paths
   (e.g. `/projects/foo/src/index.css`) which don't parse as URLs, so
   the guard never fired.

2. `@tailwindcss/browser@4` only resolves a hardcoded set of `@import`
   specifiers (`tailwindcss`, `tailwindcss/preflight`,
   `tailwindcss/theme`, `tailwindcss/utilities`) and throws
   'The browser build does not support @import for <x>' for everything
   else, so plugin packages couldn't be preserved as external either.

Detect CSS importers with a plain string match and split behavior:
`tailwindcss` and its subpaths stay external so the v4 runtime can
handle them, while other bare CSS imports fall through to the normal
esm.sh resolution path. esm.sh redirects CSS-only packages to their
`.css` entry and `onLoad` picks `loader: "css"` via the content-type
mapping, so the dependency is bundled inline. The combined CSS then
lands in the `<style type="text/tailwindcss">` block where the v4
runtime can process v4 directives (`@custom-variant`, `@theme`, etc.)
from third-party plugins.
This commit is contained in:
Alex Gleason committed 2026-04-26 22:17:14 -05:00
1 parent 1fd3d23d4f
commit af2436a3b8
1 file changed
+16 -8
+16 -8
View File
@@ -255,14 +255,22 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
const { pathname } = new URL(args.importer);
if (/\.css$/.test(pathname)) {
return; // CSS imports don't have external dependencies
}
} catch {
// not a URL; continue
// When the importer is a CSS file, treat `@import "tailwindcss"`
// and its subpaths (`tailwindcss/preflight`, `/theme`, `/utilities`)
// as external so the Tailwind v4 `@tailwindcss/browser` runtime can
// process them at runtime (the v4 runtime special-cases these and
// rejects all other `@import` specifiers). Any other bare CSS
// `@import` falls through to the normal CDN resolution below, which
// will load the dependency as CSS content and bundle it inline
// (esm.sh redirects bare package specifiers for CSS-only packages
// to their `.css` entry, which the `onLoad` handler picks up via
// the `text/css` content-type -> `loader: "css"` mapping).
const importerIsCss = /\.css(?:\?|$)/.test(args.importer ?? "");
if (importerIsCss && /^tailwindcss(?:\/|$)/.test(path)) {
return {
path: args.path,
external: true,
};
}
// Check if this is a file: dependency