CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vite-node

Vite as Node.js runtime that enables on-demand evaluation with full ESM and TypeScript support

Pending
Overview
Eval results
Files

source-maps.mddocs/

Source Maps

Inline source map support for debugging with accurate stack traces in transformed code. Provides essential debugging capabilities by mapping transformed code back to original source locations.

Capabilities

Source Map Installation

Install source map support for Node.js to enable accurate stack traces.

/**
 * Install source map support for Node.js error stack traces
 * Enables accurate line numbers and file names in errors from transformed code
 */
function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;

interface InstallSourceMapSupportOptions {
  /** Function to retrieve source map for a given source file */
  getSourceMap: (source: string) => EncodedSourceMap | null | undefined;
}

Usage Examples:

import { installSourcemapsSupport } from "vite-node/source-map";
import { ViteNodeServer } from "vite-node/server";

const nodeServer = new ViteNodeServer(viteServer);

// Install source map support
installSourcemapsSupport({
  getSourceMap: (source) => nodeServer.getSourceMap(source),
});

// Now errors will show original source locations instead of transformed code

Inline Source Map Processing

Add inline source maps to transformation results for debugging support.

/**
 * Add inline source map to transformation result
 * Embeds source map as base64 data URL in the transformed code
 */
function withInlineSourcemap(
  result: TransformResult,
  options: {
    /** Project root path for resolving relative paths */
    root: string;
    /** File path of the transformed module */
    filepath: string;
    /** Skip first line mapping for Vite 6+ compatibility */
    noFirstLineMapping?: boolean;
  }
): TransformResult;

interface TransformResult {
  /** Transformed JavaScript/TypeScript code */
  code: string;
  /** Source map for the transformation */
  map?: any;
}

Usage Examples:

import { withInlineSourcemap } from "vite-node/source-map";

// Add inline source map to transformation
const transformedResult = await viteServer.transformRequest('./app.ts');
const withSourceMap = withInlineSourcemap(transformedResult, {
  root: '/project/root',
  filepath: '/project/root/src/app.ts',
  noFirstLineMapping: viteVersion >= 6,
});

// Code now includes inline source map
console.log(withSourceMap.code.includes('sourceMappingURL')); // true

Source Map Extraction

Extract source maps from transformed code containing inline source maps.

/**
 * Extract source map from code containing inline source map
 * Parses base64-encoded source map data from transformed code
 */
function extractSourceMap(code: string): EncodedSourceMap | null;

Usage Examples:

import { extractSourceMap } from "vite-node/source-map";

// Extract source map from transformed code
const code = `
console.log('hello');
//# sourceMappingSource=vite-node
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozfQ==
`;

const sourceMap = extractSourceMap(code);
if (sourceMap) {
  console.log('Version:', sourceMap.version);
  console.log('Sources:', sourceMap.sources);
}

Source Map Types

Source maps use standard formats for maximum compatibility.

/** Standard encoded source map format */
type EncodedSourceMap = {
  version: number;
  sources: string[];
  names: string[];
  mappings: string;
  file?: string;
  sourceRoot?: string;
  sourcesContent?: (string | null)[];
};

Source Map Features

Vite-Node Specific Source Maps

Vite-node adds special handling for source maps:

  • Inline Embedding: Source maps are embedded directly in transformed code
  • Path Normalization: Ensures consistent path handling across platforms
  • Vite Integration: Seamless integration with Vite's source map generation
  • Debug Support: Special markers for vite-node generated source maps

Path Resolution

Source maps handle complex path resolution scenarios:

// Handles various path formats
const result = withInlineSourcemap(transformResult, {
  root: '/project',
  filepath: '/project/src/components/App.vue',
});

// Resolves relative paths correctly in source map
// Original: '/project/src/components/App.vue'  
// In source map: 'src/components/App.vue' (relative to root)

First Line Mapping

Special handling for import statements and module headers:

// For Vite 5 and earlier - adds first line mapping
const older = withInlineSourcemap(result, {
  root: projectRoot,
  filepath: filePath,
  noFirstLineMapping: false,
});

// For Vite 6+ - skips first line mapping (handled by Vite)
const newer = withInlineSourcemap(result, {
  root: projectRoot, 
  filepath: filePath,
  noFirstLineMapping: true,
});

Debugging Workflow

Complete debugging setup with source maps:

import { createServer } from "vite";
import { ViteNodeRunner } from "vite-node/client";
import { ViteNodeServer } from "vite-node/server";
import { installSourcemapsSupport } from "vite-node/source-map";

async function setupDebugging() {
  // Create Vite server
  const server = await createServer({
    // Enable source maps in Vite
    build: { sourcemap: true },
  });

  // Create vite-node server
  const nodeServer = new ViteNodeServer(server, {
    // Enable inline source maps
    sourcemap: 'inline',
  });

  // Install source map support
  installSourcemapsSupport({
    getSourceMap: (source) => nodeServer.getSourceMap(source),
  });

  // Create runner
  const runner = new ViteNodeRunner({
    root: server.config.root,
    fetchModule: (id) => nodeServer.fetchModule(id),
    resolveId: (id, importer) => nodeServer.resolveId(id, importer),
  });

  // Execute with accurate stack traces
  try {
    await runner.executeFile('./src/app.ts');
  } catch (error) {
    // Error stack trace will show original TypeScript locations
    console.error(error.stack);
  }
}

Performance Considerations

Source map processing is optimized for development use:

  • Lazy Generation: Source maps are only processed when needed
  • Caching: Source maps are cached to avoid repeated processing
  • Minimal Overhead: Inline embedding has minimal impact on execution speed
  • Debug Mode: Source map features can be disabled in production

Error Handling

Source map functionality handles edge cases gracefully:

  • Missing Source Maps: Functions continue to work without source maps
  • Invalid Format: Graceful handling of malformed source map data
  • Path Resolution: Fallback handling for unresolvable source paths

Common patterns:

// Safe source map extraction
try {
  const map = extractSourceMap(code);
  if (map) {
    // Use source map
    processSourceMap(map);
  }
} catch (error) {
  // Fallback without source map
  console.warn('Source map extraction failed:', error.message);
}

// Safe source map installation
try {
  installSourcemapsSupport({
    getSourceMap: (source) => {
      try {
        return nodeServer.getSourceMap(source);
      } catch {
        return null; // Fallback for missing maps
      }
    },
  });
} catch (error) {
  console.warn('Source map support installation failed:', error.message);
}

Integration with Development Tools

Source maps work seamlessly with development tools:

  • VS Code: Breakpoints work correctly in original TypeScript files
  • Chrome DevTools: Stack traces show original source locations
  • Node.js Inspector: Debugging sessions use original file paths
  • Error Reporting: Production error tracking with source map support

Install with Tessl CLI

npx tessl i tessl/npm-vite-node

docs

cli.md

client.md

hmr.md

index.md

server.md

source-maps.md

utils.md

tile.json