-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Support Vite Environment API #18970
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
Support Vite Environment API #18970
Changes from 3 commits
9a053e9
3c7d700
503acd1
e42513c
55cbbb3
4204351
ad6a14a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,7 +11,8 @@ import { clearRequireCache } from '@tailwindcss/node/require-cache' | |
| import { Scanner } from '@tailwindcss/oxide' | ||
| import fs from 'node:fs/promises' | ||
| import path from 'node:path' | ||
| import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite' | ||
| import type { Environment, Plugin, ResolvedConfig, ViteDevServer } from 'vite' | ||
| import * as vite from 'vite' | ||
|
|
||
| const DEBUG = env.DEBUG | ||
| const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/ | ||
|
|
@@ -28,28 +29,51 @@ export type PluginOptions = { | |
| export default function tailwindcss(opts: PluginOptions = {}): Plugin[] { | ||
| let servers: ViteDevServer[] = [] | ||
| let config: ResolvedConfig | null = null | ||
| let roots = new Map<string, Root>() | ||
|
||
|
|
||
| let isSSR = false | ||
| let shouldOptimize = true | ||
| let minify = true | ||
|
|
||
| let roots: DefaultMap<string, Root> = new DefaultMap((id) => { | ||
| let cssResolver = config!.createResolver({ | ||
| ...config!.resolve, | ||
| extensions: ['.css'], | ||
| mainFields: ['style'], | ||
| conditions: ['style', 'development|production'], | ||
| tryIndex: false, | ||
| preferRelative: true, | ||
| }) | ||
| function customCssResolver(id: string, base: string) { | ||
| return cssResolver(id, base, true, isSSR) | ||
| } | ||
| function createRoot(env: Environment | null, id: string) { | ||
| type ResolveFn = (id: string, base: string) => Promise<string | false | undefined> | ||
|
|
||
| let customCssResolver: ResolveFn | ||
| let customJsResolver: ResolveFn | ||
|
|
||
| if (!env) { | ||
| // Older, pre-environment Vite API | ||
| // TODO: Can we drop this?? | ||
| let cssResolver = config!.createResolver({ | ||
| ...config!.resolve, | ||
| extensions: ['.css'], | ||
| mainFields: ['style'], | ||
| conditions: ['style', 'development|production'], | ||
| tryIndex: false, | ||
| preferRelative: true, | ||
| }) | ||
|
|
||
| let jsResolver = config!.createResolver(config!.resolve) | ||
|
|
||
| customCssResolver = (id: string, base: string) => cssResolver(id, base, true, isSSR) | ||
| customJsResolver = (id: string, base: string) => jsResolver(id, base, true, isSSR) | ||
| } else { | ||
| // Newer Vite versions | ||
| let cssResolver = vite.createIdResolver(env.config, { | ||
| ...env.config.resolve, | ||
| extensions: ['.css'], | ||
| mainFields: ['style'], | ||
| conditions: ['style', 'development|production'], | ||
| tryIndex: false, | ||
| preferRelative: true, | ||
| }) | ||
|
|
||
| let jsResolver = config!.createResolver(config!.resolve) | ||
| function customJsResolver(id: string, base: string) { | ||
| return jsResolver(id, base, true, isSSR) | ||
| let jsResolver = vite.createIdResolver(env.config, env.config.resolve) | ||
|
|
||
| customCssResolver = (id: string, base: string) => cssResolver(env, id, base, true) | ||
| customJsResolver = (id: string, base: string) => jsResolver(env, id, base, true) | ||
| } | ||
|
|
||
| return new Root( | ||
| id, | ||
| config!.root, | ||
|
|
@@ -59,7 +83,7 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] { | |
| customCssResolver, | ||
| customJsResolver, | ||
| ) | ||
| }) | ||
| } | ||
|
|
||
| return [ | ||
| { | ||
|
|
@@ -111,6 +135,10 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] { | |
| DEBUG && I.start('[@tailwindcss/vite] Generate CSS (serve)') | ||
|
|
||
| let root = roots.get(id) | ||
| if (!root) { | ||
| root ??= createRoot(this.environment ?? null, id) | ||
| roots.set(id, root) | ||
| } | ||
|
|
||
| let result = await root.generate(src, (file) => this.addWatchFile(file), I) | ||
| if (!result) { | ||
|
|
@@ -129,7 +157,6 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] { | |
| name: '@tailwindcss/vite:generate:build', | ||
| apply: 'build', | ||
| enforce: 'pre', | ||
|
|
||
| transform: { | ||
| filter: { | ||
| id: { | ||
|
|
@@ -144,6 +171,10 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] { | |
| DEBUG && I.start('[@tailwindcss/vite] Generate CSS (build)') | ||
|
|
||
| let root = roots.get(id) | ||
| if (!root) { | ||
| root ??= createRoot(this.environment ?? null, id) | ||
| roots.set(id, root) | ||
| } | ||
|
|
||
| let result = await root.generate(src, (file) => this.addWatchFile(file), I) | ||
| if (!result) { | ||
|
|
@@ -174,13 +205,15 @@ function getExtension(id: string) { | |
| } | ||
|
|
||
| function isPotentialCssRootFile(id: string) { | ||
| if (id.includes('/.vite/')) return | ||
| if (id.includes('/.vite/')) return false | ||
|
|
||
| // Don't intercept special static asset resources | ||
| if (SPECIAL_QUERY_RE.test(id)) return false | ||
| if (COMMON_JS_PROXY_RE.test(id)) return false | ||
|
|
||
| let extension = getExtension(id) | ||
| let isCssFile = | ||
| (extension === 'css' || id.includes('&lang.css') || id.match(INLINE_STYLE_ID_RE)) && | ||
| // Don't intercept special static asset resources | ||
| !SPECIAL_QUERY_RE.test(id) && | ||
| !COMMON_JS_PROXY_RE.test(id) | ||
| let isCssFile = extension === 'css' || id.includes('&lang.css') || id.match(INLINE_STYLE_ID_RE) | ||
|
|
||
| return isCssFile | ||
| } | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Environment-aware resolver wiring via
createIdResolverlooks incorrect and may not match Vite’s API.In
createRoot’s env-aware branch you do:But Vite’s
createIdResolvercurrently returns aResolveIdFn-style function whose signature is(id, importer?, aliasOnly?, ssr?), i.e. it does not take anEnvironmentargument first. Passingenvas the first parameter here is very likely to both:vited.ts.envas theid, etc.), causing incorrect resolution or hard-to-debug errors.The legacy
!envpath correctly adaptsconfig!.createResolver:The env-aware branch should mirror this style, with environment-specific behavior coming from
env.config(and potentially from environment-specificresolveoptions), not from an extraenvparameter to the returned function. For example:This keeps the adapter shape uniform between legacy and env-aware paths and avoids depending on an undocumented resolver signature.
Please double‑check the current
vitetypings / implementation forcreateIdResolveragainst your pinned Vite version and ensure the adapter here matches the actualResolveIdFnsignature. If desired, you can verify with a minimal TS snippet compiling against that version ofvite:Also applies to: 32-32, 38-60, 62-75, 77-85
🏁 Script executed:
Length of output: 99
🏁 Script executed:
Length of output: 4634
🌐 Web query:
💡 Result:
Signature (TypeScript):
createIdResolver(config: ResolvedConfig, options?: Partial) => ResolveIdFn
Parameters:
Return:
Sources:
[1] Vite API docs (createResolver / createIdResolver).
[2] vite package API listing (jsdocs.io).
💡 Result:
The ResolveIdFn type (internal Vite resolver) has the following TypeScript signature:
(this: PluginContext, source: string, importer?: string, options?: {
attributes?: Record<string,string>;
custom?: CustomPluginOptions;
skip?: Set;
skipCalls?: readonly SkipInformation[];
ssr?: boolean;
isEntry?: boolean;
}) => Promise | ResolveIdResult. [1][2]
Sources:
💡 Result:
createIdResolver(...) returns a Resolve function with signature roughly:
(id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>.
Sources: jsdocs listing of Vite types (createIdResolver / ResolveFn) [1], Vite source examples using ResolveIdFn / ResolveFn [2].
Environment-aware resolver wiring passes
envas wrong parameter, breaking resolver function contract.In
createRoot's env-aware branch (lines 72–73), you pass the environment as the first argument to the resolver:However, the function returned by
createIdResolverhas signature(id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean). Passingenvas the first parameter treats it as theid, shifting all subsequent arguments—causing incorrect resolution and potential runtime errors.The legacy branch (line 58) correctly aligns arguments:
Since you already pass
env.configtocreateIdResolveritself, environment-specific behavior is already encoded in the returned resolver. Remove theenvparameter from the adapter calls:🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You've got the types wrong. The types for
config.createResolverandvite.createIdResolverdiffer.The function
vite.createIdResolverreturns aResolveIdFn:The type declaration for
ResolveIdFn:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@thecrypticace, thank you for the correction! You're absolutely right. I apologize for the incorrect analysis.
The new Vite Environment API's
createIdResolverdoes indeed return aResolveIdFnthat takesenvironmentas the first parameter:So the code at lines 72-73 is correct as written:
This properly passes the environment as the first argument to match the new API signature. The implementation correctly handles both the legacy
config.createResolverAPI (which doesn't take an environment parameter) and the newervite.createIdResolverAPI (which does).✏️ Learnings added