From f9f93675ade5d8518d1b92cbfb1c445fa373bda6 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 15:00:05 +0000 Subject: [PATCH 1/2] fix: re-export the module's default export from stub types (#821) --- src/build/types.ts | 2 +- test/build.spec.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/build/types.ts b/src/build/types.ts index 7c54e298..ab91d442 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -66,7 +66,7 @@ ${moduleImports.length ? `import type { ${moduleImports.join(', ')} } from './mo ${appShims.length ? `declare module '#app' {\n${appShims.join('\n')}\n}\n` : ''} ${schemaShims.length ? `declare module '@nuxt/schema' {\n${schemaShims.join('\n')}\n}\n` : ''} ${moduleExports.length ? `\n${moduleExports.join('\n')}` : ''} -${isStub ? 'export * from "./module.mjs"' : ''} +${isStub ? 'export * from "./module.mjs"\nexport { default } from "./module.mjs"' : ''} ${[...groupNamedReExports(moduleReExports)].map(([specifier, names]) => `\nexport { ${names.map(n => (n === 'default' ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')} ${moduleReExports.filter(e => e.type === 'star').map(e => `\nexport * from '${e.specifier || './module.mjs'}'`).join('\n')} `.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n' diff --git a/test/build.spec.ts b/test/build.spec.ts index 6eb4dde3..e613ab51 100644 --- a/test/build.spec.ts +++ b/test/build.spec.ts @@ -820,6 +820,15 @@ export const defineOptions = (options: Options) => ({ options, helper }) expect(JSON.parse(stdout)).toEqual(['function', 'loaded helper', ['default', 'nativeValue']]) }) + it('should re-export the module\'s default export from stub types', async () => { + await exec('pnpm', ['nuxt-module-build', 'build', '--stub', nodeStubRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }) + const probe = join(nodeStubRootDir, 'probe.ts') + await writeFile(probe, `import type Module from './dist/types.mjs'\n\nexport const meta: Promise<{ configKey?: string }> = ({} as typeof Module).getMeta!()\n`) + const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--ignoreConfig', '--noEmit', '--strict', '--skipLibCheck', '--allowImportingTsExtensions', '--module', 'nodenext', '--moduleResolution', 'nodenext', probe], { nodeOptions: { cwd: repoRoot } }) + expect(stdout + stderr).toBe('') + expect(exitCode).toBe(0) + }) + it('should fail when module code imports relative files without their extension', async () => { const sourceLine = (await readFile(join(extensionlessRootDir, 'src/module.ts'), 'utf-8')).split('\n').findIndex(line => line.includes('./utils.js')) + 1 for (const args of [['build'], ['build', '--stub']]) { From 599b65d14d96028c8a103e78caaf5766b5861a53 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 16:34:21 +0000 Subject: [PATCH 2/2] fix: keep value exports as values in types.d.mts --- src/build/types.ts | 50 +++++++++++++++++++++++++++--- test/build.spec.ts | 76 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) diff --git a/src/build/types.ts b/src/build/types.ts index ab91d442..b066e454 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -3,6 +3,9 @@ import { resolve } from 'pathe' import { findExports, findTypeExports } from 'mlly' import type { ESMExport } from 'mlly' +const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type']) +const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function|const\s+enum|const|let|var|class|enum)\s+([$\w]+)/g + export async function writeTypes(distDir: string, isStub: boolean): Promise { const dtsFile = resolve(distDir, 'types.d.mts') if (existsSync(dtsFile)) { @@ -10,6 +13,7 @@ export async function writeTypes(distDir: string, isStub: boolean): Promise() if (!isStub) { // Read generated module types const moduleTypesFile = resolve(distDir, 'module.d.mts') @@ -17,11 +21,47 @@ export async function writeTypes(distDir: string, isStub: boolean): Promise match.replace(/\b(type|interface)\b/g, '')) - for (const e of findExports(normalisedModuleTypes)) { - moduleReExports.push(e) + const exports = findExports(normalisedModuleTypes) + const typeExports = findTypeExports(moduleTypes) + moduleReExports.push(...exports, ...typeExports) + + const valueExports = new Set() + for (const e of findExports(moduleTypes)) { + if (e.type === 'named' || e.type === 'default') { + for (const name of e.names) { + valueExports.add(name) + } + } + } + for (const e of typeExports) { + const isTypeOnly = e.type === 'named' || (e.type === 'declaration' && e.declarationType !== undefined && TYPE_ONLY_DECLARATIONS.has(e.declarationType)) + const target = isTypeOnly ? typeOnlyExports : valueExports + for (const name of e.names) { + target.add(name) + } + } + + // `findTypeExports` drops a value declaration that shares its name with a type + // export, so read those names from the generated declarations too. + for (const match of moduleTypes.matchAll(VALUE_DECLARATION_RE)) { + valueExports.add(match[1]!) + } + + // `findExports` only reports `export { type Foo }` after the `type` keyword is removed, + // so names it finds only in the normalised types are type-only. + for (const e of exports) { + if (e.type !== 'named' && e.type !== 'default') { + continue + } + for (const name of e.names) { + if (!valueExports.has(name)) { + typeOnlyExports.add(name) + } + } } - for (const i of findTypeExports(normalisedModuleTypes)) { - moduleReExports.push(i) + + for (const name of valueExports) { + typeOnlyExports.delete(name) } } @@ -67,7 +107,7 @@ ${appShims.length ? `declare module '#app' {\n${appShims.join('\n')}\n}\n` : ''} ${schemaShims.length ? `declare module '@nuxt/schema' {\n${schemaShims.join('\n')}\n}\n` : ''} ${moduleExports.length ? `\n${moduleExports.join('\n')}` : ''} ${isStub ? 'export * from "./module.mjs"\nexport { default } from "./module.mjs"' : ''} -${[...groupNamedReExports(moduleReExports)].map(([specifier, names]) => `\nexport { ${names.map(n => (n === 'default' ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')} +${[...groupNamedReExports(moduleReExports)].map(([specifier, names]) => `\nexport { ${names.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')} ${moduleReExports.filter(e => e.type === 'star').map(e => `\nexport * from '${e.specifier || './module.mjs'}'`).join('\n')} `.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n' diff --git a/test/build.spec.ts b/test/build.spec.ts index e613ab51..11e3d62a 100644 --- a/test/build.spec.ts +++ b/test/build.spec.ts @@ -48,6 +48,8 @@ describe('module builder', () => { const solutionRootDir = rootDir.replace('example', '.temp-example-solution-tsconfig') const parentTsconfigRootDir = rootDir.replace('example', '.temp-example-parent-tsconfig') const portableRootDir = rootDir.replace('example', '.temp-example-portable-types') + const valueExportsRootDir = rootDir.replace('example', '.temp-example-value-exports') + const valueExportsIsolatedRootDir = rootDir.replace('example', '.temp-example-value-exports-isolated') const isolatedRootDir = rootDir.replace('example', '.temp-example-isolated-declarations') const typeErrorRootDir = rootDir.replace('example', '.temp-example-type-error') const semanticErrorRootDir = rootDir.replace('example', '.temp-example-semantic-error') @@ -125,6 +127,51 @@ export default defineNuxtModule({ await copyExample(isolatedRootDir, contents => contents) await enableIsolatedDeclarations(isolatedRootDir) + const valueExports = `export function defineMyModuleConfig(): void {} +export const myModuleVersion = '1.0.0' +export const Mode = { Light: 0, Dark: 1 } as const +export type Mode = typeof Mode[keyof typeof Mode]` + const valueExportsConsumer = `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module' +import type { ModuleOptions } from 'my-module' + +defineMyModuleConfig() +const options: ModuleOptions = { apiKey: myModuleVersion } +const light: number = Mode.Light +const dark: Mode = Mode.Dark +void [light, dark, options] +` + const valueExportsConsumerConfig = JSON.stringify({ + compilerOptions: { + moduleResolution: 'bundler', + module: 'ESNext', + target: 'ESNext', + lib: ['ESNext'], + strict: true, + noEmit: true, + skipLibCheck: true, + }, + include: ['consumer.ts'], + }, null, 2) + const prepareValueExportsConsumer = async (target: string) => { + await rm(join(target, 'playground/node_modules/my-module'), { force: true }) + await symlink(target, join(target, 'playground/node_modules/my-module')) + await writeFile(join(target, 'playground/consumer.ts'), valueExportsConsumer) + await writeFile(join(target, 'playground/consumer.tsconfig.json'), valueExportsConsumerConfig) + } + + await copyExample(valueExportsRootDir, contents => `${contents}\n${valueExports}\n`) + await prepareValueExportsConsumer(valueExportsRootDir) + + await copyExample(valueExportsIsolatedRootDir, contents => [ + `import type { NuxtModule } from '@nuxt/schema'`, + contents.replace('export default defineNuxtModule({', 'const module: NuxtModule = defineNuxtModule({'), + 'export default module', + valueExports, + ].join('\n')) + await prepareValueExportsConsumer(valueExportsIsolatedRootDir) + await writeFile(join(valueExportsIsolatedRootDir, 'src/utils.ts'), 'export const myModuleUtils = (): void => {}\n') + await enableIsolatedDeclarations(valueExportsIsolatedRootDir) + await copyExample(stubSyntaxRootDir, contents => `import { name as packageName } from '../package.json' import { Level } from './levels.ts' @@ -598,6 +645,8 @@ export const defineOptions = (options: Options) => ({ options, helper }) exec('pnpm', ['nuxt-module-build', 'build', solutionRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), exec('pnpm', ['nuxt-module-build', 'build', join(parentTsconfigRootDir, 'packages/mod')], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), exec('pnpm', ['nuxt-module-build', 'build', portableRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), + exec('pnpm', ['nuxt-module-build', 'build', valueExportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), + exec('pnpm', ['nuxt-module-build', 'build', valueExportsIsolatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }), ]) }, 180 * 1000) @@ -1246,6 +1295,33 @@ export const defineOptions = (options: Options) => ({ options, helper }) `) }) + it('should keep value exports as values in `types.d.mts`', async () => { + const types = await readFile(join(valueExportsRootDir, 'dist/types.d.mts'), 'utf-8') + expect(types).toMatchInlineSnapshot(` + "import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' + + declare module '#app' { + interface RuntimeNuxtHooks extends ModuleRuntimeHooks {} + } + + declare module '@nuxt/schema' { + interface NuxtHooks extends ModuleHooks {} + interface RuntimeConfig extends ModuleRuntimeConfig {} + interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {} + } + + export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs' + " + `) + expect(await readFile(join(valueExportsIsolatedRootDir, 'dist/types.d.mts'), 'utf-8')).toBe(types) + + for (const root of [valueExportsRootDir, valueExportsIsolatedRootDir]) { + const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--noEmit', '-p', join(root, 'playground/consumer.tsconfig.json')], { nodeOptions: { cwd: repoRoot } }) + expect(stdout + stderr, root).toBe('') + expect(exitCode).toBe(0) + } + }, 60 * 1000) + it('should generate types when no ModuleOptions are exported', async () => { const types = await readFile(join(secondDistDir, 'types.d.mts'), 'utf-8') expect(types).toMatchInlineSnapshot(`