@@ -16,6 +16,40 @@ import { build } from "esbuild"
16
16
import type { Plugin , PluginBuild , BuildOptions } from "esbuild"
17
17
import glob from "glob"
18
18
19
+ // Plugin to fix CommonJS imports by appending .cjs to require statements
20
+ const fixCjsImportsPlugin = ( ) : Plugin => ( {
21
+ name : "fix-cjs-imports" ,
22
+ setup ( build : PluginBuild ) {
23
+ // Run in the onEnd hook after all files have been written
24
+ build . onEnd ( ( result ) => {
25
+ // Only proceed if the build is successful
26
+ if ( result . errors . length === 0 ) {
27
+ // Get the output directory from the build options
28
+ const outdir = build . initialOptions . outdir
29
+ if ( ! outdir ) return
30
+
31
+ // Find all .cjs files in the output directory
32
+ const files = glob . sync ( `${ outdir } /**/*.cjs` )
33
+
34
+ files . forEach ( ( file ) => {
35
+ let content = fs . readFileSync ( file , "utf8" )
36
+
37
+ // Replace all require('./something') with require('./something.cjs')
38
+ content = content . replace ( / r e q u i r e \( [ " ' ] ( \. [ ^ " ' ] + ) [ " ' ] \) / g, ( match , importPath ) => {
39
+ // Don't add .cjs if it already has an extension
40
+ if ( path . extname ( importPath ) !== "" ) {
41
+ return match
42
+ }
43
+ return `require('${ importPath } .cjs')`
44
+ } )
45
+
46
+ fs . writeFileSync ( file , content )
47
+ } )
48
+ }
49
+ } )
50
+ }
51
+ } )
52
+
19
53
const entryPoints = glob . sync ( "./src/**/*.ts" , {
20
54
ignore : [ "./src/**/*.test.ts" , "./src/mod.ts" , "./src/middleware.ts" , "./src/deno/**/*.ts" ]
21
55
} )
@@ -65,6 +99,8 @@ const cjsBuild = () =>
65
99
outbase : "./src" ,
66
100
outdir : "./dist/cjs" ,
67
101
format : "cjs" ,
102
+ outExtension : { ".js" : ".cjs" } ,
103
+ plugins : [ fixCjsImportsPlugin ( ) ] ,
68
104
tsconfig : "tsconfig.cjs.json"
69
105
} )
70
106
0 commit comments