@@ -305,11 +305,21 @@ export function rolldownDepPlugin(
305305const matchesEntireLine = ( text : string ) => `^${ escapeRegex ( text ) } $`
306306
307307// rolldown (and esbuild) doesn't transpile `require('foo')` into `import` statements if 'foo' is externalized
308- // https://github.com/evanw/esbuild/issues/566#issuecomment-735551834
308+ // https://rolldown.rs/in-depth/bundling-cjs#require-external-modules
309309export function rolldownCjsExternalPlugin (
310310 externals : string [ ] ,
311311 platform : 'node' | 'browser' | 'neutral' ,
312- ) : Plugin {
312+ ) : Plugin | undefined {
313+ // Skip this plugin for `platform: 'node'` as `require` is available in Node
314+ // and that is more accurate than converting to `import`
315+ if ( platform === 'node' ) {
316+ return undefined
317+ }
318+
319+ // Apply this plugin for `platform: 'browser'` as `require` is not available in browser and
320+ // converting to `import` would be necessary to make the code work
321+ platform satisfies 'browser' | 'neutral'
322+
313323 const filter = new RegExp ( externals . map ( matchesEntireLine ) . join ( '|' ) )
314324
315325 return {
@@ -323,34 +333,26 @@ export function rolldownCjsExternalPlugin(
323333 external : 'absolute' ,
324334 }
325335 }
326-
327- if ( filter . test ( id ) ) {
328- const kind = options . kind
329- // preserve `require` for node because it's more accurate than converting it to import
330- if ( kind === 'require-call' && platform !== 'node' ) {
331- return {
332- id : cjsExternalFacadeNamespace + id ,
333- }
334- }
335-
336+ if ( options . kind === 'require-call' ) {
336337 return {
337- id,
338- external : 'absolute' ,
338+ id : cjsExternalFacadeNamespace + id ,
339339 }
340340 }
341+ return {
342+ id,
343+ external : 'absolute' ,
344+ }
341345 } ,
342346 } ,
343347 load : {
344348 filter : { id : prefixRegex ( cjsExternalFacadeNamespace ) } ,
345349 handler ( id ) {
346- if ( id . startsWith ( cjsExternalFacadeNamespace ) ) {
347- const idWithoutNamespace = id . slice ( cjsExternalFacadeNamespace . length )
348- return {
349- code : `\
350+ const idWithoutNamespace = id . slice ( cjsExternalFacadeNamespace . length )
351+ return {
352+ code : `\
350353import * as m from ${ JSON . stringify ( nonFacadePrefix + idWithoutNamespace ) } ;
351354module.exports = ${ isNodeBuiltin ( idWithoutNamespace ) ? 'm.default' : '{ ...m }' } ;
352355` ,
353- }
354356 }
355357 } ,
356358 } ,
0 commit comments