33
44const KeplerPackage = require ( './package' ) ;
55
6- const PRESETS = [ '@babel/preset-env' , '@babel/preset-react' , '@babel/preset-typescript' ] ;
7- const PLUGINS = [
6+ // Plugins shared by both CJS and ESM builds.
7+ const SHARED_PLUGINS = [
88 [ '@babel/plugin-transform-typescript' , { isTSX : true , allowDeclareFields : true } ] ,
9- '@babel/plugin-transform-modules-commonjs' ,
109 '@babel/plugin-transform-class-properties' ,
1110 '@babel/plugin-transform-optional-chaining' ,
1211 '@babel/plugin-transform-logical-assignment-operators' ,
1312 '@babel/plugin-transform-nullish-coalescing-operator' ,
1413 '@babel/plugin-transform-export-namespace-from' ,
15- [
16- '@babel/transform-runtime' ,
17- {
18- regenerator : true
19- }
20- ] ,
2114 [
2215 'search-and-replace' ,
2316 {
@@ -30,22 +23,35 @@ const PLUGINS = [
3023 }
3124 ]
3225] ;
33- const ENV = {
34- test : {
35- plugins : [ 'istanbul' ]
36- } ,
37- debug : {
38- sourceMaps : 'inline' ,
39- retainLines : true
40- }
41- } ;
4226
4327module . exports = function babel ( api ) {
44- api . cache ( true ) ;
28+ // Cache per BABEL_ENV so that CJS and ESM builds get separate cached results.
29+ api . cache . using ( ( ) => process . env . BABEL_ENV || process . env . NODE_ENV || 'development' ) ;
30+
31+ const isEsm = api . env ( 'esm' ) ;
32+ const isTest = api . env ( 'test' ) ;
33+ const isDebug = api . env ( 'debug' ) ;
34+
35+ // ESM build: modules:false preserves import/export so Vite/esbuild can tree-shake.
36+ // CJS build (default / test): transforms import/export to require/module.exports.
37+ const presets = [
38+ [ '@babel/preset-env' , isEsm ? { modules : false } : { } ] ,
39+ '@babel/preset-react' ,
40+ '@babel/preset-typescript'
41+ ] ;
42+
43+ const plugins = [
44+ ...SHARED_PLUGINS ,
45+ // CJS and test builds need the CommonJS transform; ESM must omit it.
46+ ...( isEsm ? [ ] : [ '@babel/plugin-transform-modules-commonjs' ] ) ,
47+ // Runtime helpers: ESM variant uses ESM imports, no require() calls.
48+ [ '@babel/transform-runtime' , { regenerator : true , ...( isEsm ? { useESModules : true } : { } ) } ] ,
49+ ...( isTest ? [ 'istanbul' ] : [ ] )
50+ ] ;
4551
4652 return {
47- presets : PRESETS ,
48- plugins : PLUGINS ,
49- env : ENV
53+ presets,
54+ plugins,
55+ ... ( isDebug ? { sourceMaps : 'inline' , retainLines : true } : { } )
5056 } ;
5157} ;
0 commit comments