Overview of Module Transforms in swc
mainThe swc_ecma_transforms_module crate is responsible for lowering ECMAScript module (ESM) syntax into legacy module formats.
Supported Formats
- CommonJS: Produces
require()calls andmodule.exports. - AMD: Produces
define()calls with dependency arrays and factory bodies. - UMD: Produces an adapter IIFE with a shared factory body.
- SystemJS: Lowers modules into a
System.registerformat (documented separately).
Transformation Pipeline
Most transforms (CommonJS, AMD, UMD) follow a shared pipeline:
- Top-level
thisrewrite: Replacesthiswithundefined(unlessConfig::allow_top_level_thisis enabled). - Collection:
SourceModule::collectwalks declarations and records linkage. - Stripping:
syntax_strip::lowerremoves module syntax (likeimport/export) while preserving executable code. - Reduction:
ModuleRecordEntryReducerconverts entries intoImportMapand export getters. - Emission: Format-specific emitters generate the final code (e.g.,
requirefor CJS,definefor AMD). - Binding Rewrite: Local import references are rewritten using the generated
ImportMap.