import { calculateHashesForCreateNodes, getNamedInputs, getReadyCheckReadyWhen, PluginCache, hashObject, workspaceDataDirectory, retryOnRequireEsmRace, } from '@nx/devkit/internal'; import { CreateNodesContext, createNodesFromFiles, CreateNodes, detectPackageManager, getPackageManagerCommand, joinPathFragments, ProjectConfiguration, TargetConfiguration, normalizePath, } from '@nx/devkit'; import { getLockFileName, getRootTsConfigFileName } from '@nx/js'; import { walkTsconfigExtendsChain, type RawTsconfigJsonCache, addBuildAndWatchDepsTargets, createTypecheckTarget, isUsingTsSolutionSetup as _isUsingTsSolutionSetup, selectTypecheckTsConfig, } from '@nx/js/internal'; import { existsSync, readdirSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; import { loadViteDynamicImport } from '../utils/executor-utils'; import picomatch = require('picomatch'); import type { ResolvedConfig } from 'vite'; export interface VitePluginOptions { buildTargetName?: string; /** * @deprecated Use devTargetName instead. This option will be removed in Nx 22. */ serveTargetName?: string; devTargetName?: string; previewTargetName?: string; serveStaticTargetName?: string; /** * Name of the `vue-tsc` typecheck target inferred for Vue projects. Other * projects get their typecheck target from `@nx/js/typescript`. */ typecheckTargetName?: string | false; /** * The compiler used to typecheck Vue projects. Defaults to `vue-tsc` when the * `vite:vue` plugin is detected. Set `vue-tsc` to force the target when * detection misses your setup, or `tsc`/`tsgo` to skip it and rely on * `@nx/js/typescript`. */ compiler?: 'tsc' | 'tsgo' | 'vue-tsc'; watchDepsTargetName?: string; buildDepsTargetName?: string; } type ViteTargets = Pick< ProjectConfiguration, 'targets' | 'metadata' | 'projectType' >; const viteConfigGlob = '**/vite.config.{js,ts,mjs,mts,cjs,cts}'; export const createNodes: CreateNodes = [ viteConfigGlob, async (configFilePaths, options, context) => { const optionsHash = hashObject(options); const normalizedOptions = normalizeOptions(options); const cachePath = join(workspaceDataDirectory, `vite-${optionsHash}.hash`); const targetsCache = new PluginCache(cachePath); const isUsingTsSolutionSetup = _isUsingTsSolutionSetup(); const { roots: projectRoots, configFiles: validConfigFiles } = configFilePaths.reduce( (acc, configFile) => { const potentialRoot = dirname(configFile); if (checkIfConfigFileShouldBeProject(potentialRoot, context)) { acc.roots.push(potentialRoot); acc.configFiles.push(configFile); } return acc; }, { roots: [], configFiles: [], } as { roots: string[]; configFiles: string[]; } ); const detectedPackageManager = detectPackageManager(context.workspaceRoot); const pmc = getPackageManagerCommand(detectedPackageManager); const lockfile = getLockFileName(detectedPackageManager); const tsconfigChainsByProjectRoot = collectTsconfigInputsByProjectRoot( projectRoots, context.workspaceRoot ); const hashes = await calculateHashesForCreateNodes( projectRoots, { ...normalizedOptions, isUsingTsSolutionSetup }, context, projectRoots.map((root) => [ lockfile, ...(tsconfigChainsByProjectRoot.get(root) ?? []), ]) ); try { return await createNodesFromFiles( async (configFile, _, context, idx) => { const projectRoot = dirname(configFile); // Do not create a project if package.json and project.json isn't there. const siblingFiles = readdirSync( join(context.workspaceRoot, projectRoot) ); const tsConfigFiles = siblingFiles.filter((p) => picomatch('tsconfig*{.json,.*.json}')(p) ) ?? []; const hasReactRouterConfig = siblingFiles.some((configFile) => { const parts = configFile.split('.'); return ( parts[0] === 'react-router' && parts[1] === 'config' && parts.length > 2 ); }); const hash = hashes[idx] + configFile; if (!targetsCache.has(hash)) { targetsCache.set( hash, await buildViteTargets( configFile, projectRoot, normalizedOptions, tsConfigFiles, hasReactRouterConfig, isUsingTsSolutionSetup, context, pmc ) ); } const { projectType, metadata, targets } = targetsCache.get(hash); const project: ProjectConfiguration = { root: projectRoot, targets, metadata, }; // If project is buildable, then the project type. // If it is not buildable, then leave it to other plugins/project.json to set the project type. if (project.targets[normalizedOptions.buildTargetName]) { project.projectType = projectType; } return { projects: { [projectRoot]: project, }, }; }, validConfigFiles, options, context ); } finally { targetsCache.writeToDisk(); } }, ]; export const createNodesV2 = createNodes; async function buildViteTargets( configFilePath: string, projectRoot: string, options: VitePluginOptions, tsConfigFiles: string[], hasReactRouterConfig: boolean, isUsingTsSolutionSetup: boolean, context: CreateNodesContext, pmc: ReturnType ): Promise { const absoluteConfigFilePath = joinPathFragments( context.workspaceRoot, configFilePath ); // Workaround for the `build$3 is not a function` error that we sometimes see in agents. // This should be removed later once we address the issue properly try { const importEsbuild = () => new Function('return import("esbuild")')(); await importEsbuild(); } catch { // do nothing } const { resolveConfig } = await loadViteDynamicImport(); const resolveConfigForInference = async (command: 'build' | 'serve') => { // Vite always resolves default server settings, so capture whether the // config or one of its plugins set them before that happens. let hasExplicitServer = false; const config = await retryOnRequireEsmRace(() => resolveConfig( { configFile: absoluteConfigFilePath, mode: 'development', root: projectRoot, // The serve resolution is optional and allowed to fail. logLevel: command === 'serve' ? 'silent' : undefined, plugins: [ { name: 'nx-capture-explicit-vite-server', enforce: 'post' as const, config: { order: 'post' as const, handler(userConfig: { server?: unknown }) { hasExplicitServer = Boolean(userConfig.server); }, }, }, ], }, command ) ); return { config, hasExplicitServer }; }; const { config: viteBuildConfig, hasExplicitServer: hasBuildServerConfig } = await resolveConfigForInference('build'); const metadata: ProjectConfiguration['metadata'] = {}; const { buildOutputs, isBuildable } = getOutputs( viteBuildConfig, projectRoot, context.workspaceRoot ); const namedInputs = getNamedInputs(projectRoot, context); const targets: Record = {}; if (hasReactRouterConfig) { // If we have a react-router config, we can skip the rest of the targets return { targets, metadata: {}, projectType: 'application' }; } const hasRemixPlugin = viteBuildConfig.plugins && viteBuildConfig.plugins.some((p) => p.name === 'remix'); if (!hasRemixPlugin && isBuildable) { targets[options.buildTargetName] = await buildTarget( options.buildTargetName, namedInputs, buildOutputs, projectRoot, isUsingTsSolutionSetup, pmc ); let hasServeConfig = hasBuildServerConfig; if (viteBuildConfig.build?.lib && !hasServeConfig) { try { hasServeConfig = (await resolveConfigForInference('serve')) .hasExplicitServer; } catch { // Build-only configs may reject serve mode. } } // If running in library mode, then there is nothing to serve. if (!viteBuildConfig.build?.lib || hasServeConfig) { const signals = !!viteBuildConfig.plugins?.some( (p) => p.name === 'nx-ready-signal' ); const devTarget = serveTarget( projectRoot, configFilePath, signals, isUsingTsSolutionSetup, pmc, namedInputs ); targets[options.serveTargetName] = { ...devTarget, metadata: { ...devTarget.metadata, deprecated: 'Use devTargetName instead. This option will be removed in Nx 22.', }, }; targets[options.devTargetName] = devTarget; targets[options.previewTargetName] = previewTarget( projectRoot, configFilePath, signals, options.buildTargetName, pmc, namedInputs ); targets[options.serveStaticTargetName] = serveStaticTarget( options, isUsingTsSolutionSetup, namedInputs ); } } const hasVuePlugin = viteBuildConfig.plugins?.some( (p) => p.name === 'vite:vue' || p.name === 'vite:vue2' ); // @nx/js/typescript provides tsc typecheck targets but can't run vue-tsc. const usesVueTsc = (options.compiler ?? (hasVuePlugin ? 'vue-tsc' : 'tsc')) === 'vue-tsc'; if ( usesVueTsc && options.typecheckTargetName !== false && tsConfigFiles.length ) { const technologies = hasVuePlugin ? ['typescript', 'vue'] : ['typescript']; const tsConfig = selectTypecheckTsConfig(tsConfigFiles); if (!isUsingTsSolutionSetup) { if (tsConfig) { targets[options.typecheckTargetName] = createTypecheckTarget({ mode: 'noEmit', projectRoot: joinPathFragments(projectRoot), pmc, tsConfig, compiler: 'vue-tsc', namedInputs, technologies, }); } } else if (tsConfigFiles.includes('tsconfig.json')) { targets[options.typecheckTargetName] = createTypecheckTarget({ mode: 'build', projectRoot: joinPathFragments(projectRoot), pmc, compiler: 'vue-tsc', targetName: options.typecheckTargetName, buildTargetName: targets[options.buildTargetName] ? options.buildTargetName : undefined, namedInputs, technologies, }); } } addBuildAndWatchDepsTargets( context.workspaceRoot, projectRoot, targets, options, pmc ); return { targets, metadata, projectType: viteBuildConfig.build?.lib ? 'library' : 'application', }; } async function buildTarget( buildTargetName: string, namedInputs: { [inputName: string]: any[]; }, outputs: string[], projectRoot: string, isUsingTsSolutionSetup: boolean, pmc: ReturnType ) { const buildTarget: TargetConfiguration = { command: `vite build`, options: { cwd: joinPathFragments(projectRoot) }, cache: true, dependsOn: [`^${buildTargetName}`], inputs: [ ...buildInputs(namedInputs), // A dependency consumed as built is read from its build's outputs. { dependentTasksOutputFiles: '**/*', transitive: true }, ], outputs, metadata: { technologies: ['vite'], description: `Run Vite build`, help: { command: `${pmc.exec} vite build --help`, example: { options: { sourcemap: true, manifest: 'manifest.json', }, }, }, }, }; if (isUsingTsSolutionSetup) { buildTarget.syncGenerators = ['@nx/js:typescript-sync']; } return buildTarget; } function buildInputs(namedInputs: { [inputName: string]: any[]; }): TargetConfiguration['inputs'] { return [ ...('production' in namedInputs ? ['production', '^production'] : ['default', '^default']), { externalDependencies: ['vite'], }, ]; } function serveTarget( projectRoot: string, configFilePath: string, signals: boolean, isUsingTsSolutionSetup: boolean, pmc: ReturnType, namedInputs: { [inputName: string]: any[] } ) { const targetConfig: TargetConfiguration = { continuous: true, inputs: buildInputs(namedInputs), command: `vite`, options: { cwd: joinPathFragments(projectRoot), }, readyWhen: getServerReadyWhen(configFilePath, 'serve', signals), metadata: { technologies: ['vite'], description: `Starts Vite dev server`, help: { command: `${pmc.exec} vite --help`, example: { options: { port: 3000, }, }, }, }, }; if (isUsingTsSolutionSetup) { targetConfig.syncGenerators = ['@nx/js:typescript-sync']; } return targetConfig; } function previewTarget( projectRoot: string, configFilePath: string, signals: boolean, buildTargetName: string, pmc: ReturnType, namedInputs: { [inputName: string]: any[] } ) { const targetConfig: TargetConfiguration = { continuous: true, inputs: buildInputs(namedInputs), command: `vite preview`, dependsOn: [buildTargetName], options: { cwd: joinPathFragments(projectRoot), }, readyWhen: getServerReadyWhen(configFilePath, 'preview', signals), metadata: { technologies: ['vite'], description: `Locally preview Vite production build`, help: { command: `${pmc.exec} vite preview --help`, example: { options: { port: 3000, }, }, }, }, }; return targetConfig; } function serveStaticTarget( options: VitePluginOptions, isUsingTsSolutionSetup: boolean, namedInputs: { [inputName: string]: any[] } ) { const targetConfig: TargetConfiguration = { continuous: true, dependsOn: [options.buildTargetName], inputs: buildInputs(namedInputs), executor: '@nx/web:file-server', options: { buildTarget: `${options.buildTargetName}`, spa: true, }, readyWhen: { signal: true }, }; if (isUsingTsSolutionSetup) { targetConfig.syncGenerators = ['@nx/js:typescript-sync']; } return targetConfig; } // A config that loads nxReadySignal() reports when the server listens. // Otherwise the check resolves the config when the task runs, with the task's // env and options, and waits for the server's port. function getServerReadyWhen( configFilePath: string, command: 'serve' | 'preview', signals: boolean ): TargetConfiguration['readyWhen'] { return signals ? { signal: true } : getReadyCheckReadyWhen( '@nx/vite/ready-check', basename(configFilePath), command ); } function getOutputs( viteBuildConfig: ResolvedConfig | undefined, projectRoot: string, workspaceRoot: string ): { buildOutputs: string[]; isBuildable: boolean; } { // TODO(jack): Remove this cast when @nx/vite switches to moduleResolution: // "nodenext". Vite 8's rolldown types are ESM-only (.d.mts) and not // resolvable under moduleResolution: "node", which breaks rolldownOptions // on ResolvedConfig. const { build } = viteBuildConfig as any; const buildOutputPath = normalizeOutputPath( build?.outDir, projectRoot, workspaceRoot, 'dist' ); const isBuildable = Boolean( build?.lib || viteBuildConfig?.builder?.buildApp || build?.rollupOptions?.input || // Vite <8 build?.rolldownOptions?.input || // Vite >=8 existsSync(join(workspaceRoot, projectRoot, 'index.html')) ); return { buildOutputs: [buildOutputPath], isBuildable, }; } function normalizeOutputPath( outputPath: string | undefined, projectRoot: string, workspaceRoot: string, path: 'dist' ): string | undefined { if (!outputPath) { if (projectRoot === '.') { return `{projectRoot}/${path}`; } else { return `{workspaceRoot}/${path}/{projectRoot}`; } } else { if (isAbsolute(outputPath)) { return `{workspaceRoot}/${normalizePath(relative(workspaceRoot, outputPath))}`; } else { if (outputPath.startsWith('..')) { return joinPathFragments('{workspaceRoot}', projectRoot, outputPath); } else { return joinPathFragments('{projectRoot}', outputPath); } } } } function normalizeOptions(options: VitePluginOptions): VitePluginOptions { options ??= {}; options.buildTargetName ??= 'build'; options.serveTargetName ??= 'serve'; options.devTargetName ??= 'dev'; options.previewTargetName ??= 'preview'; options.serveStaticTargetName ??= 'serve-static'; options.typecheckTargetName ??= 'typecheck'; return options; } /** * Collects tsconfig files that Vite's esbuild-based config bundler reads * but are outside the project root (and thus not covered by `default`). * * Vite < 8 uses esbuild's Build API to bundle config files. esbuild walks * UP from the entry point, reading and parsing every `tsconfig.json` in * every ancestor directory plus their `extends` chains. Vite >= 8 uses * rolldown with `tsconfig: false`, but pnpm can resolve different Vite * versions per project, so we always collect — the walk is cheap (cached * JSON reads) and over-declaring inputs for Vite 8 projects is harmless. */ function collectTsconfigInputsByProjectRoot( projectRoots: string[], workspaceRoot: string ): Map { const jsonCache: RawTsconfigJsonCache = new Map(); const result = new Map(); const rootTsConfigName = getRootTsConfigFileName(); for (const projectRoot of projectRoots) { if (projectRoot === '.') continue; const outside: string[] = []; const seen = new Set(); const projectPrefix = `${projectRoot}/`; const collect = (absolutePath: string) => { const wsRelative = relative(workspaceRoot, absolutePath) .split(sep) .join('/'); if (seen.has(wsRelative)) return; seen.add(wsRelative); if (wsRelative.startsWith('../') || wsRelative === '..') return; if ( wsRelative.startsWith('node_modules/') || wsRelative.includes('/node_modules/') ) return; if (wsRelative === projectRoot || wsRelative.startsWith(projectPrefix)) return; if (wsRelative === rootTsConfigName) return; outside.push(wsRelative); }; // Walk the project tsconfig's extends chain const projectTsconfig = join(workspaceRoot, projectRoot, 'tsconfig.json'); if (existsSync(projectTsconfig)) { walkTsconfigExtendsChain( projectTsconfig, (absPath) => { collect(absPath); return 'continue'; }, { jsonCache } ); } // Walk UP ancestor directories — esbuild reads every tsconfig.json // between the entry point and the filesystem root. let dir = dirname(projectRoot); while (dir && dir !== '.') { const ancestorTsconfig = join(workspaceRoot, dir, 'tsconfig.json'); if (existsSync(ancestorTsconfig)) { walkTsconfigExtendsChain( ancestorTsconfig, (absPath) => { collect(absPath); return 'continue'; }, { jsonCache } ); } const parent = dirname(dir); if (parent === dir) break; dir = parent; } // Check the workspace root itself (dirname loop above stops at '.') const rootTsconfig = join(workspaceRoot, 'tsconfig.json'); if (existsSync(rootTsconfig)) { walkTsconfigExtendsChain( rootTsconfig, (absPath) => { collect(absPath); return 'continue'; }, { jsonCache } ); } if (outside.length > 0) { result.set(projectRoot, outside); } } return result; } function checkIfConfigFileShouldBeProject( projectRoot: string, context: CreateNodesContext ): boolean { // Do not create a project if package.json and project.json isn't there. const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot)); if ( !siblingFiles.includes('package.json') && !siblingFiles.includes('project.json') ) { return false; } return true; }