Vite as Node.js runtime that enables on-demand evaluation with full ESM and TypeScript support
—
Server-side integration with Vite that handles module transformation, resolution, and caching through Vite's plugin system. The server component provides the bridge between Vite's transformation pipeline and the Node.js runtime execution.
Main server class that integrates with Vite's development server to provide module transformation and resolution services.
/**
* Main server class for integrating with Vite's development server
* Handles module transformation, resolution, caching, and externalization
*/
class ViteNodeServer {
constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
/** Fetch and transform a module for execution */
fetchModule(id: string, transformMode?: 'web' | 'ssr'): Promise<FetchResult>;
/** Resolve a module ID using Vite's resolution system */
resolveId(id: string, importer?: string, transformMode?: 'web' | 'ssr'): Promise<ViteNodeResolveId | null>;
/** Get source map for a transformed module */
getSourceMap(source: string): EncodedSourceMap | null;
/** Check if a module should be externalized (not transformed) */
shouldExternalize(id: string): Promise<string | false>;
/** Get total transformation duration for performance monitoring */
getTotalDuration(): number;
/** Transform a module request */
transformRequest(id: string, filepath?: string, transformMode?: 'web' | 'ssr'): Promise<TransformResult | null | undefined>;
/** Transform a module for web mode only */
transformModule(id: string, transformMode?: 'web' | 'ssr'): Promise<{ code: string | undefined }>;
/** Determine the transform mode for a given module */
getTransformMode(id: string): 'ssr' | 'web';
// Properties
server: ViteDevServer;
options: ViteNodeServerOptions;
fetchCache: Map<string, FetchCache>;
externalizeCache: Map<string, Promise<string | false>>;
debugger?: Debugger;
}
interface ViteNodeServerOptions {
/** Source map handling mode */
sourcemap?: 'inline' | boolean;
/** Dependency handling configuration */
deps?: DepsHandlingOptions;
/** Transform mode configuration for different file patterns */
transformMode?: {
ssr?: RegExp[];
web?: RegExp[];
};
/** Debug options */
debug?: DebuggerOptions;
}
interface FetchResult {
/** Transformed code */
code?: string;
/** External module path if module should be externalized */
externalize?: string;
/** Source map for the transformed code */
map?: EncodedSourceMap | null;
}
interface ViteNodeResolveId {
/** Whether module is external */
external?: boolean | 'absolute' | 'relative';
/** Resolved module ID */
id: string;
/** Additional metadata */
meta?: Record<string, any> | null;
/** Module side effects configuration */
moduleSideEffects?: boolean | 'no-treeshake' | null;
/** Synthetic named exports configuration */
syntheticNamedExports?: boolean | string | null;
}Usage Examples:
import { createServer } from "vite";
import { ViteNodeServer } from "vite-node/server";
// Create Vite development server
const viteServer = await createServer({
server: { hmr: true },
});
// Create vite-node server
const nodeServer = new ViteNodeServer(viteServer, {
sourcemap: 'inline',
deps: {
inline: ['my-package'],
external: ['heavy-dependency'],
},
});
// Fetch and transform a module
const result = await nodeServer.fetchModule('./src/app.ts');
// Resolve a module ID
const resolved = await nodeServer.resolveId('./utils', './src/app.ts');Configuration for how dependencies should be handled during transformation.
/**
* Configuration for dependency handling during module transformation
* Controls which modules are inlined vs externalized
*/
interface DepsHandlingOptions {
/** Dependencies that should always be externalized (not transformed) */
external?: (string | RegExp)[];
/** Dependencies that should be inlined (transformed), or true for all */
inline?: (string | RegExp)[] | true;
/** Specific files that should be inlined by file path */
inlineFiles?: string[];
/** Directories considered to hold Node.js modules */
moduleDirectories?: string[];
/** Cache directory for dependency resolution */
cacheDir?: string;
/** Try to guess the CJS version of a package when it's invalid ESM */
fallbackCJS?: boolean;
}Usage Examples:
const serverOptions = {
deps: {
// Always externalize these packages
external: ['lodash', /^@types\//],
// Inline these packages for transformation
inline: ['my-esm-package', /^@my-org\//],
// Inline specific files
inlineFiles: ['/path/to/specific/file.js'],
// Custom module directories
moduleDirectories: ['/node_modules/', '/custom_modules/'],
// Enable CJS fallback
fallbackCJS: true,
},
};Configure which files should be transformed in 'web' vs 'ssr' mode.
/**
* Transform mode configuration for different file patterns
* Determines whether files are processed as web or SSR modules
*/
interface TransformModeOptions {
/** RegExp patterns for files that should use SSR transformation */
ssr?: RegExp[];
/** RegExp patterns for files that should use web transformation */
web?: RegExp[];
}Usage Examples:
const serverOptions = {
transformMode: {
// Process Vue SFCs in web mode
web: [/\.vue$/],
// Process server utilities in SSR mode
ssr: [/\/server\//, /\.server\./],
},
};Configuration for debugging and development features.
/**
* Debug configuration options for development and troubleshooting
* Enables module dumping and loading for debugging transformed code
*/
interface DebuggerOptions {
/** Dump transformed modules to filesystem for inspection */
dumpModules?: boolean | string;
/** Load dumped modules from filesystem instead of transforming */
loadDumppedModules?: boolean;
}Usage Examples:
const serverOptions = {
debug: {
// Dump to default .vite-node/dump directory
dumpModules: true,
// Or dump to custom directory
dumpModules: './debug-output',
// Load from dumped files for debugging
loadDumppedModules: process.env.NODE_ENV === 'debug',
},
};Control which modules should be externalized (not transformed by Vite).
/**
* Check if a module should be externalized (not transformed)
* Returns the external module path or false if should be inlined
*/
function shouldExternalize(
id: string,
options?: DepsHandlingOptions,
cache?: Map<string, Promise<string | false>>
): Promise<string | false>;
/**
* Attempt to find a CommonJS version of an ESM module
* Useful when fallbackCJS is enabled and ESM module is invalid
*/
function guessCJSversion(id: string): string | undefined;Usage Examples:
import { shouldExternalize, guessCJSversion } from "vite-node/server";
// Check if module should be externalized
const external = await shouldExternalize('lodash');
if (external) {
// Module will be externalized, use external path
console.log(`Externalizing: ${external}`);
} else {
// Module will be inlined and transformed
console.log('Inlining module');
}
// Try to find CJS version of ESM module
const cjsVersion = guessCJSversion('/node_modules/package/es/index.js');
if (cjsVersion) {
console.log(`Found CJS alternative: ${cjsVersion}`);
}The server includes sophisticated caching mechanisms:
// Access performance data
const totalDuration = nodeServer.getTotalDuration();
console.log(`Total transformation time: ${totalDuration}ms`);The server handles various error conditions during transformation:
Common error handling patterns:
try {
const result = await nodeServer.fetchModule('./problematic-module.ts');
} catch (error) {
if (error.message.includes('Failed to load url')) {
// Handle module loading failure
} else {
// Handle transformation error
}
}