Advanced functionality including multi-source handling, custom formatting utilities, and integration helpers for complex code generation scenarios.
Handle code generation from ASTs that combine multiple source files, maintaining accurate source maps and file references.
/**
* The standard generate function supports multi-source input
* @param ast - Combined AST from multiple sources
* @param options - Generation options with source map configuration
* @param sources - Object mapping filenames to source code content
* @returns Result with consolidated source map
*/
function generate(
ast: Object,
options: GeneratorOptions,
sources: SourcesObject
): GeneratorResult;
interface SourcesObject {
[filename: string]: string;
}Usage Examples:
import generate from "babel-generator";
// Multi-source generation with source maps
const sources = {
'utils.js': 'export function helper() { return 42; }',
'main.js': 'import { helper } from "./utils"; console.log(helper());',
'config.js': 'export const API_URL = "https://api.example.com";'
};
// Assume you have a combined AST from these sources
const combinedAst = createCombinedAST(sources);
const result = generate(combinedAst, {
sourceMaps: true,
sourceMapTarget: 'bundle.js',
sourceRoot: '/src'
}, sources);
console.log(result.code); // Combined generated code
console.log(result.map.sources); // ['utils.js', 'main.js', 'config.js']Important: The babel-generator package exports only two public APIs:
// Default export function
export default function generate(
ast: Object,
opts?: GeneratorOptions,
code?: string | Object
): GeneratorResult;
// Named export class
export class CodeGenerator {
constructor(ast: Object, opts?: GeneratorOptions, code?: string | Object);
generate(): GeneratorResult;
}All internal utilities such as:
Buffer class for output managementPrinter class for AST traversalneedsWhitespace, needsParens helper functionsSourceMap class internalsAre not exported from the main module and should not be accessed directly. For advanced customization, work within the public API using the available generator options.
Usage Examples:
// Note: These utilities are internal and not exported from the main module
// They would require direct access to internal modules for advanced customization
// Advanced buffer usage (internal API - requires custom generator setup)
// const buffer = new Buffer();
// buffer.append('const x = ');
// buffer.queue('42'); // Can be removed/modified later
// const result = buffer.get();
// For public API usage, rely on the main generator function:
import generate from "babel-generator";
const result = generate(ast, {
compact: false, // Use public options for formatting control
quotes: "single"
});Patterns and utilities for integrating with build tools and bundlers.
/**
* Build tool integration patterns
*/
interface BuildIntegration {
/** Webpack loader integration */
webpackLoader(source: string, map?: Object): string;
/** Rollup plugin integration */
rollupPlugin(options: Object): Object;
/** Babel plugin integration */
babelPlugin(api: Object, options: Object): Object;
}Usage Examples:
// Webpack loader integration
function babelGeneratorLoader(source, sourceMap) {
const ast = parse(source);
// ... transform AST ...
const result = generate(ast, {
sourceMaps: !!sourceMap,
sourceMapTarget: this.resourcePath,
sourceFileName: this.resourcePath
}, source);
this.callback(null, result.code, result.map);
}
// Babel plugin integration
function customBabelPlugin(api, options) {
return {
visitor: {
Program(path) {
// Transform AST
const generated = generate(path.node, options.generatorOptions);
// Use generated code...
}
}
};
}
// Build system integration
function buildStep(inputFiles, outputFile, options) {
const combinedAst = combineFiles(inputFiles);
const result = generate(combinedAst, {
...options,
sourceMaps: true,
sourceMapTarget: outputFile
}, inputFiles);
writeFileSync(outputFile, result.code);
writeFileSync(outputFile + '.map', JSON.stringify(result.map));
}Advanced patterns for optimizing generation performance in large codebases.
/**
* Performance optimization strategies
*/
interface PerformanceOptions {
/** Lazy source map generation */
lazySourceMaps?: boolean;
/** Memory-efficient mode for large files */
streaming?: boolean;
/** Parallel processing for multi-file generation */
parallel?: boolean;
/** Cache generated output for repeated generation */
cache?: boolean;
}Usage Examples:
// Performance-optimized generation for large codebases
const optimizedResult = generate(largeAst, {
compact: true, // Reduce output size
comments: false, // Skip comment processing
sourceMaps: false, // Disable source maps for speed
lazySourceMaps: true, // Generate source maps only when accessed
streaming: true // Use streaming mode for memory efficiency
});
// Parallel multi-file generation
const files = ['file1.js', 'file2.js', 'file3.js'];
const results = await Promise.all(
files.map(file =>
generate(parseFile(file), optimizedOptions, readFile(file))
)
);