11import { existsSync , promises as fsp } from 'node:fs'
22import { pathToFileURL } from 'node:url'
3- import { dirname , resolve } from 'pathe'
3+ import { basename , dirname , join , resolve } from 'pathe'
4+ import { filename } from 'pathe/utils'
45import { readPackageJSON } from 'pkg-types'
56import { parse } from 'tsconfck'
67import type { TSConfig } from 'pkg-types'
78import { defu } from 'defu'
9+ import { anyOf , createRegExp } from 'magic-regexp'
810import { consola } from 'consola'
911import type { ModuleMeta , NuxtModule } from '@nuxt/schema'
10- import { findExports } from 'mlly'
12+ import { findExports , resolvePath } from 'mlly'
1113import { defineCommand } from 'citty'
1214
1315import { name , version } from '../../package.json'
@@ -71,7 +73,6 @@ export default defineCommand({
7173 cjsBridge : true ,
7274 } ,
7375 externals : [
74- / s r c \/ r u n t i m e / ,
7576 '@nuxt/schema' ,
7677 '@nuxt/schema-nightly' ,
7778 '@nuxt/schema-edge' ,
@@ -91,8 +92,44 @@ export default defineCommand({
9192 compilerOptions : await loadTSCompilerOptions ( entry . input ) ,
9293 } )
9394 } ,
95+ async 'rollup:options' ( ctx , options ) {
96+ options . plugins ||= [ ]
97+ if ( ! Array . isArray ( options . plugins ) )
98+ options . plugins = [ options . plugins ]
99+
100+ const runtimeEntries = ctx . options . entries . filter ( entry => entry . builder === 'mkdist' )
101+
102+ const runtimeDirs = runtimeEntries . map ( entry => basename ( entry . input ) )
103+ const RUNTIME_RE = createRegExp ( anyOf ( ...runtimeDirs ) . and ( '/' ) )
104+
105+ // Add extension for imports of runtime files in build
106+ options . plugins . unshift ( {
107+ name : 'nuxt-module-builder:runtime-externals' ,
108+ async resolveId ( id , importer ) {
109+ if ( ! RUNTIME_RE . test ( id ) )
110+ return
111+
112+ const resolved = await this . resolve ( id , importer , { skipSelf : true } )
113+ if ( ! resolved )
114+ return
115+
116+ for ( const entry of runtimeEntries ) {
117+ if ( ! resolved . id . includes ( entry . input ) )
118+ continue
119+
120+ const distFile = await resolvePath ( join ( dirname ( resolved . id . replace ( entry . input , entry . outDir ! ) ) , filename ( resolved . id ) ) )
121+ if ( distFile ) {
122+ return {
123+ external : true ,
124+ id : distFile ,
125+ }
126+ }
127+ }
128+ } ,
129+ } )
130+ } ,
94131 async 'rollup:done' ( ctx ) {
95- // Generate CommonJS stub
132+ // Generate CommonJS stub
96133 await writeCJSStub ( ctx . options . outDir )
97134
98135 // Load module meta
0 commit comments