11import type { UserConfig } from 'vitepress'
22import path from 'path'
33import { fileURLToPath } from 'url'
4- import { viteCommonjs as baseViteCommonjs } from '@originjs/vite-plugin-commonjs '
4+ import esbuild from 'esbuild '
55type Plugin = Extract <
66 NonNullable < NonNullable < UserConfig [ 'vite' ] > [ 'plugins' ] > [ number ] ,
77 { name : string }
@@ -27,27 +27,63 @@ export function vitePluginRequireResolve(): Plugin {
2727}
2828
2929export function viteCommonjs ( ) : Plugin {
30- const base = baseViteCommonjs ( {
31- include : [ libRoot ] ,
32- skipPreBuild : true
33- } ) as Plugin
3430 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' ,
3732 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
4136 }
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 )
4945 }
50- return result
46+ return undefined
5147 }
5248 }
5349}
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