Source map generation capabilities for maintaining debugging information when converting ASTs to JavaScript code.
Options for enabling and configuring source map generation.
interface SourceMapOptions {
/** Enable source map generation */
sourceMaps?: boolean;
/** Filename for the generated code (appears in source map) */
sourceMapTarget?: string;
/** Root path for source map URLs */
sourceRoot?: string;
/** Original source filename (for single-file source maps) */
sourceFileName?: string;
}Usage Examples:
import generate from "babel-generator";
// Basic source map generation
const result = generate(ast, {
sourceMaps: true,
sourceMapTarget: "output.js",
sourceFileName: "input.js"
}, originalSourceCode);
console.log(result.code); // Generated JavaScript
console.log(result.map); // Source map objectGenerate source maps for transformations of a single source file.
/**
* Generate code with source map from single source file
* @param ast - The transformed AST
* @param options - Must include sourceMaps: true and filename info
* @param sourceCode - Original source code string
* @returns Result with code and source map
*/
function generateWithSourceMap(
ast: Object,
options: SourceMapOptions & { sourceMaps: true },
sourceCode: string
): GeneratorResult & { map: Object };Usage Examples:
// Transform and generate with source map
const originalCode = 'const x = 1; const y = 2;';
const ast = parse(originalCode);
// ... transform AST ...
const result = generate(ast, {
sourceMaps: true,
sourceMapTarget: 'transformed.js',
sourceFileName: 'original.js'
}, originalCode);
// Use source map with debugging tools
const sourceMap = result.map;
console.log(sourceMap.version); // Source map version
console.log(sourceMap.sources); // ['original.js']
console.log(sourceMap.mappings); // Base64 encoded mappingsGenerate source maps when combining multiple source files into a single output.
/**
* Generate code with source map from multiple source files
* @param ast - Combined AST from multiple sources
* @param options - Source map configuration
* @param sources - Object mapping filenames to source code
* @returns Result with code and consolidated source map
*/
function generateMultiFileSourceMap(
ast: Object,
options: SourceMapOptions & { sourceMaps: true },
sources: { [filename: string]: string }
): GeneratorResult & { map: Object };Usage Examples:
// Multi-file source map generation
const sources = {
'module1.js': 'export const a = 1;',
'module2.js': 'export const b = 2;',
'module3.js': 'export const c = 3;'
};
// Create combined AST from multiple files
const combinedAst = combineModules(sources);
const result = generate(combinedAst, {
sourceMaps: true,
sourceMapTarget: 'bundle.js',
sourceRoot: '/src'
}, sources);
// Source map will reference all original files
console.log(result.map.sources); // ['module1.js', 'module2.js', 'module3.js']Structure of the generated source map object.
interface SourceMapObject {
/** Source map format version (always 3) */
version: number;
/** Original source filenames */
sources: string[];
/** Source content (if includeContent: true) */
sourcesContent?: string[];
/** Symbol names used in mappings */
names: string[];
/** Base64 VLQ encoded mappings */
mappings: string;
/** Generated code filename */
file?: string;
/** Source root for relative paths */
sourceRoot?: string;
}Access to raw mapping data for advanced source map processing.
interface GeneratorResult {
code: string;
map?: SourceMapObject;
/** Raw mapping entries for custom source map processing */
rawMappings?: Array<{
generated: { line: number; column: number };
original: { line: number; column: number };
source: string;
name?: string;
}>;
}Usage Examples:
const result = generate(ast, { sourceMaps: true }, sourceCode);
// Access raw mappings for custom processing
if (result.rawMappings) {
result.rawMappings.forEach(mapping => {
console.log(`${mapping.generated.line}:${mapping.generated.column} -> ` +
`${mapping.original.line}:${mapping.original.column} in ${mapping.source}`);
});
}Integration patterns with build tools and development workflows.
// Common integration patterns:
// 1. Inline source maps
const inlineResult = generate(ast, {
sourceMaps: true,
sourceMapTarget: 'output.js'
}, sourceCode);
const inlineCode = inlineResult.code +
'\n//# sourceMappingURL=data:application/json;base64,' +
Buffer.from(JSON.stringify(inlineResult.map)).toString('base64');
// 2. External source map files
const externalResult = generate(ast, {
sourceMaps: true,
sourceMapTarget: 'output.js'
}, sourceCode);
// Write separate .map file
fs.writeFileSync('output.js.map', JSON.stringify(externalResult.map));
const codeWithMapReference = externalResult.code + '\n//# sourceMappingURL=output.js.map';
// 3. Development server integration
const devResult = generate(ast, {
sourceMaps: true,
sourceMapTarget: '/virtual/output.js',
sourceRoot: '/project/src'
}, sourceCode);Helper utilities for working with source maps.
/**
* Utilities available from internal classes (advanced usage)
*/
class SourceMap {
constructor(opts: SourceMapOptions, code: string | Object);
/** Get final source map object */
get(): SourceMapObject;
/** Get raw mapping entries */
getRawMappings(): Array<Object>;
/** Mark a source location mapping */
mark(
generatedLine: number,
generatedColumn: number,
line: number,
column: number,
identifierName?: string,
filename?: string
): void;
}Best practices for debugging generated code with source maps.
Usage Examples:
// Development build with comprehensive source maps
const debugBuild = generate(ast, {
sourceMaps: true,
sourceMapTarget: 'app.js',
sourceFileName: 'src/app.js',
sourceRoot: '/',
retainLines: true, // Help preserve line numbers
comments: true // Keep comments for context
}, sourceCode);
// Production build with optimized source maps
const prodBuild = generate(ast, {
sourceMaps: true,
sourceMapTarget: 'app.min.js',
sourceRoot: '/src',
minified: true // Minify but keep source maps
}, sourceCode);