Vite as Node.js runtime that enables on-demand evaluation with full ESM and TypeScript support
—
Core module execution engine that runs transformed JavaScript/TypeScript code with proper context isolation and dependency management. The client runtime is responsible for executing modules in Node.js with Vite's transformation support.
Main runner class for executing modules with Vite's transformation pipeline.
/**
* Main runner class for executing modules with proper isolation and context management
* Handles module caching, dependency tracking, and execution context preparation
*/
class ViteNodeRunner {
constructor(options: ViteNodeRunnerOptions);
/** Execute a file by file path */
executeFile(file: string): Promise<any>;
/** Execute a module by its ID */
executeId(rawId: string): Promise<any>;
/** Resolve a URL for a given ID */
resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>;
/** Check if an ID should be resolved */
shouldResolveId(id: string, _importee?: string): boolean;
/** Check if a module should be interoped */
shouldInterop(path: string, mod: any): boolean;
/** Import a module with interop support */
interopedImport(path: string): Promise<any>;
/** Prepare execution context for a module */
prepareContext(context: Record<string, any>): Record<string, any>;
// Properties
root: string;
debug: boolean;
moduleCache: ModuleCacheMap;
}
interface ViteNodeRunnerOptions {
/** Root directory for module resolution */
root: string;
/** Function to fetch and transform modules */
fetchModule: FetchFunction;
/** Optional function to resolve module IDs */
resolveId?: ResolveIdFunction;
/** Optional function to create HMR hot context */
createHotContext?: CreateHotContextFunction;
/** Base URL for module resolution */
base?: string;
/** Module cache instance (optional, will create default if not provided) */
moduleCache?: ModuleCacheMap;
/** Module execution info tracking */
moduleExecutionInfo?: ModuleExecutionInfo;
/** Whether to interop default exports (default: true) */
interopDefault?: boolean;
/** Stub modules for specific request patterns */
requestStubs?: Record<string, any>;
/** Enable debug mode */
debug?: boolean;
}Usage Examples:
import { ViteNodeRunner } from "vite-node/client";
// Basic runner setup
const runner = new ViteNodeRunner({
root: "/path/to/project",
fetchModule: (id) => server.fetchModule(id),
resolveId: (id, importer) => server.resolveId(id, importer),
});
// Execute a TypeScript file
const result = await runner.executeFile("./src/app.ts");
// Execute by module ID
const moduleResult = await runner.executeId("virtual:my-module");Extended Map for intelligent module caching with dependency tracking and invalidation.
/**
* Extended Map for module caching with dependency tracking and smart invalidation
* Provides methods for cache management and dependency tree invalidation
*/
class ModuleCacheMap extends Map<string, ModuleCache> {
/** Normalize a file system path for use as cache key */
normalizePath(fsPath: string): string;
/** Update existing cache entry with partial data */
update(fsPath: string, mod: ModuleCache): this;
/** Set cache entry by module ID */
setByModuleId(modulePath: string, mod: ModuleCache): this;
/** Get cache entry by module ID, creating empty entry if not exists */
getByModuleId(modulePath: string): ModuleCache & Required<Pick<ModuleCache, 'imports' | 'importers'>>;
/** Delete cache entry by module ID */
deleteByModuleId(modulePath: string): boolean;
/** Invalidate a single module cache entry */
invalidateModule(mod: ModuleCache): boolean;
/** Invalidate dependency tree upwards (modules that depend on given modules) */
invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/** Invalidate dependency tree downwards (dependencies of given modules) */
invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/** Get source map for a module */
getSourceMap(id: string): EncodedSourceMap | null;
}
interface ModuleCache {
/** Promise for module loading/execution */
promise?: Promise<any>;
/** Exported values from the module */
exports?: any;
/** Whether module has been fully evaluated */
evaluated?: boolean;
/** Whether module is currently being resolved */
resolving?: boolean;
/** Transformed source code */
code?: string;
/** Source map for the module */
map?: EncodedSourceMap;
/** Set of module IDs that import this module */
importers?: Set<string>;
/** Set of module IDs that this module imports */
imports?: Set<string>;
}Usage Examples:
import { ModuleCacheMap } from "vite-node/client";
// Create custom cache
const cache = new ModuleCacheMap();
// Cache a module
cache.set("/path/to/module.js", {
exports: { default: "value" },
evaluated: true,
});
// Invalidate dependency tree
const invalidated = cache.invalidateDepTree(["/path/to/changed.js"]);
// Get source map
const map = cache.getSourceMap("/path/to/module.js");Performance tracking for module execution timing and statistics.
/**
* Map tracking execution performance for loaded modules
* Provides timing information and self-time calculation
*/
type ModuleExecutionInfo = Map<string, ModuleExecutionInfoEntry>;
interface ModuleExecutionInfoEntry {
/** Start offset for the module execution */
startOffset: number;
/** The duration that was spent executing the module */
duration: number;
/** The time that was spent executing the module itself and externalized imports */
selfTime: number;
}Default stub modules for common Vite client requests.
/**
* Default request stubs for common Vite client modules
* Provides mock implementations for client-side dependencies in server environment
*/
const DEFAULT_REQUEST_STUBS: Record<string, Record<string, unknown>>;Usage Examples:
import { DEFAULT_REQUEST_STUBS } from "vite-node/client";
// Use default stubs
const runner = new ViteNodeRunner({
root: "/project",
fetchModule: myFetchFunction,
requestStubs: {
...DEFAULT_REQUEST_STUBS,
"my-custom-stub": { mock: "value" },
},
});The client runtime handles various error conditions:
Common error handling patterns:
try {
await runner.executeFile("./problematic-file.ts");
} catch (error) {
if (error.code === 'ERR_MODULE_NOT_FOUND') {
// Handle missing module
} else {
// Handle other execution errors
}
}