1
1
import type { UserConfig } from 'vitepress'
2
2
import path from 'path'
3
3
import { fileURLToPath } from 'url'
4
- import { viteCommonjs as baseViteCommonjs } from '@originjs/vite-plugin-commonjs '
4
+ import esbuild from 'esbuild '
5
5
type Plugin = Extract <
6
6
NonNullable < NonNullable < UserConfig [ 'vite' ] > [ 'plugins' ] > [ number ] ,
7
7
{ name : string }
@@ -27,27 +27,63 @@ export function vitePluginRequireResolve(): Plugin {
27
27
}
28
28
29
29
export function viteCommonjs ( ) : Plugin {
30
- const base = baseViteCommonjs ( {
31
- include : [ libRoot ] ,
32
- skipPreBuild : true
33
- } ) as Plugin
34
30
return {
35
- ...base ,
36
- // The `@originjs/vite-plugin-commonjs` is 'serve' only, but use it in 'build' as well.
31
+ name : 'vite-plugin-cjs-to-esm' ,
37
32
apply : ( ) => true ,
38
- async transform ( code , id , options ) {
39
- if ( typeof base . transform !== 'function' ) {
40
- return null
33
+ async transform ( code , id ) {
34
+ if ( ! id . startsWith ( libRoot ) ) {
35
+ return undefined
41
36
}
42
- const result = await base . transform . call ( this , code , id , options )
43
- if ( result && typeof result === 'object' && result . code ) {
44
- return {
45
- ...result ,
46
- // Replace it with null, because blanks can be given to the sourcemap and cause an error.
47
- map : undefined
48
- }
37
+ const base = transformRequire ( code )
38
+ try {
39
+ const transformed = esbuild . transformSync ( base , {
40
+ format : 'esm'
41
+ } )
42
+ return transformed . code
43
+ } catch ( e ) {
44
+ console . error ( 'Transform error. base code:\n' + base , e )
49
45
}
50
- return result
46
+ return undefined
51
47
}
52
48
}
53
49
}
50
+
51
+ /**
52
+ * Transform `require()` to `import`
53
+ */
54
+ function transformRequire ( code : string ) {
55
+ if ( ! code . includes ( 'require' ) ) {
56
+ return code
57
+ }
58
+ const modules = new Map ( )
59
+ const replaced = code . replace (
60
+ / ( \/ \/ [ ^ \n \r ] * | \/ \* [ \s \S ] * ?\* \/ ) | \b r e q u i r e \s * \( \s * ( [ " ' ] .* ?[ " ' ] ) \s * \) / gu,
61
+ ( match , comment , moduleString ) => {
62
+ if ( comment ) {
63
+ return match
64
+ }
65
+
66
+ let id =
67
+ '__' +
68
+ moduleString . replace ( / [ ^ a - z A - Z 0 - 9 _ $ ] + / gu, '_' ) +
69
+ Math . random ( ) . toString ( 32 ) . substring ( 2 )
70
+ while ( code . includes ( id ) || modules . has ( id ) ) {
71
+ id += Math . random ( ) . toString ( 32 ) . substring ( 2 )
72
+ }
73
+ modules . set ( id , moduleString )
74
+ return id
75
+ }
76
+ )
77
+
78
+ return (
79
+ [ ...modules ]
80
+ . map ( ( [ id , moduleString ] ) => {
81
+ return `import * as __temp_${ id } from ${ moduleString } ;
82
+ const ${ id } = __temp_${ id } .default || __temp_${ id } ;
83
+ `
84
+ } )
85
+ . join ( '' ) +
86
+ ';\n' +
87
+ replaced
88
+ )
89
+ }
0 commit comments