This example demonstrates how to use Codegen to automatically analyze and reorganize TypeScript module re-exports through shared directories. The script makes this process simple by handling all the tedious manual updates automatically.
Note
This codemod helps maintain clean module boundaries and improves code organization by centralizing shared exports.
The script automates the entire reorganization process in a few key steps:
-
Export Analysis
for export_stmt in file.export_statements: for export in export_stmt.exports: if export.is_reexport() and not export.is_external_export: all_reexports.append(export)
- Automatically identifies re-exports in shared directories
- Analyzes export patterns and dependencies
- Uses Codegen's intelligent code analysis engine
-
Shared File Management
resolved_public_file = export.resolved_symbol.filepath.replace("src/", "src/shared/") if not codebase.has_file(resolved_public_file): target_file = codebase.create_file(resolved_public_file, sync=True)
- Creates or updates shared export files
- Maintains proper file structure
- Handles path resolution automatically
-
Import Updates
# Updates imports to use new shared paths new_path = usage.file.ts_config.translate_import_path(resolved_public_file) new_import = f'import {{ {name} }} from "{new_path}"'
- Updates all import statements to use new paths
- Maintains proper TypeScript path resolution
- Handles different import types (normal, type)
-
Zero Manual Updates
- Codegen SDK handles all file creation and updates
- No tedious export management
-
Consistent Structure
- Ensures all shared exports follow the same pattern
- Maintains clean module boundaries
-
Safe Transformations
- Validates changes before applying them
- Preserves existing functionality
// Before: Direct module import
import { validateEmail } from '../module_a/src/functions';
// After: Import through shared
import { validateEmail } from '../module_a/src/shared';// Before: Multiple export files
export { foo } from './foo';
export { bar } from './bar';
// After: Consolidated in shared
export * from '../functions';-
Better Module Boundaries
- Clear public API for each module
- Centralized shared functionality
-
Improved Maintainability
- Easier to track dependencies
- Simplified import paths
-
Code Organization
- Consistent export structure
- Reduced import complexity
The script will:
- 🎯 Start the reexport organization
- 📁 Analyze shared directories
- 🔄 Process and update exports
- ✨ Create shared export files
- 🧹 Clean up redundant exports
- TypeScript Modules
- Export/Import Documentation
- Codegen Documentation
- Tutorial on Analyzing and Organizing Re-exports
- More on exports
Feel free to submit issues and enhancement requests!