From d8888fbb1fafddedf875c72c6ec13ab1507f6f7f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 22:38:30 +0000 Subject: [PATCH 1/8] test: point the paths of copied fixtures' `.nuxt` at the installed packages --- test/engines.spec.ts | 2 +- test/utils.ts | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/test/engines.spec.ts b/test/engines.spec.ts index f0968c57..92100833 100644 --- a/test/engines.spec.ts +++ b/test/engines.spec.ts @@ -240,7 +240,7 @@ it.skipIf(reasons.typescript7)('should build and prepare a module whose own `typ expect(output).toMatch(/the typescript declaration engine uses typescript@7\.1\.\S+, installed as typescript\n/) } for (const sub of ['dist', '.nuxt/module-builder/declarations']) { - const quotes = (text: string | undefined) => sub === 'dist' ? text : text?.replaceAll('\'', '"') + const quotes = (text: string | undefined) => text?.replaceAll('\'', '"') const own = Object.fromEntries(Object.entries(await declarationsOf(dirs.ownTypescript7!, sub)).map(([file, text]) => [file, quotes(text)])) const typescript = await declarationsOf(dirs.typescript!, sub) expect(Object.keys(own)).toContain(sub === 'dist' ? 'extra/math.d.mts' : 'src/runtime/plugins/plugin.d.ts') diff --git a/test/utils.ts b/test/utils.ts index acc50a88..84b0e410 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -3,7 +3,7 @@ import { cp, mkdir, readdir, readFile, rm, symlink, writeFile } from 'node:fs/pr import { availableParallelism } from 'node:os' import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' -import { dirname, join } from 'pathe' +import { dirname, join, relative, resolve } from 'pathe' import { exec } from 'tinyexec' import ts from 'typescript' import { expect, onTestFailed } from 'vitest' @@ -120,6 +120,7 @@ export async function fixture(dir: string, { from = exampleDir, config = DEFAULT await mkdir(dirname(root), { recursive: true }) await cp(from, root, { recursive: true }) await rm(join(root, 'dist'), { recursive: true, force: true }) + await rebaseBuildDirPaths(from, root) const pkgPath = join(root, 'package.json') const { build, publishConfig: _, ...published } = publishedPackage(JSON.parse(await readFile(pkgPath, 'utf-8'))) const copied = config === false ? { ...published, build } : published @@ -150,6 +151,27 @@ export async function fixture(dir: string, { from = exampleDir, config = DEFAULT return root } +/** Points the `paths` of the tsconfigs in `root/.nuxt`, copied from `from/.nuxt`, that lead out of `from` at the same files from `root`. */ +async function rebaseBuildDirPaths(from: string, root: string) { + const buildDir = join(root, '.nuxt') + const files = existsSync(buildDir) ? (await readdir(buildDir)).filter(file => /^tsconfig.*\.json$/.test(file)) : [] + for (const file of files) { + const path = join(buildDir, file) + const config = JSON.parse(await readFile(path, 'utf-8')) + const paths: Record | undefined = config.compilerOptions?.paths + if (!paths) { + continue + } + for (const [alias, targets] of Object.entries(paths)) { + paths[alias] = targets.map((target) => { + const original = resolve(from, '.nuxt', target) + return relative(from, original).startsWith('..') ? relative(buildDir, original) : target + }) + } + await writeFile(path, JSON.stringify(config, null, 2)) + } +} + export const listFiles = async (dir: string) => (await readdir(dir, { recursive: true })).map(file => file.replaceAll('\\', '/')).sort() export const read = (...segments: string[]) => readFile(join(...segments), 'utf-8') From d549bd294a286d2319fec486bff8cfc6c4e7f783 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 22:41:11 +0000 Subject: [PATCH 2/8] fix: generate declarations with the generated `paths` that a module's own replace --- docs/5.typescript.md | 2 ++ docs/upgrade-v2.md | 6 ++++ src/build/build.ts | 26 +++++++++++++-- src/diagnostics.ts | 12 +++++++ src/transpile/tsconfig.ts | 50 +++++++++++++++++++++++++++-- test/builder.spec.ts | 66 +++++++++++++++++++++++++++++++++++++++ test/unit.spec.ts | 23 +++++++++++++- test/utils.ts | 4 +-- 8 files changed, 181 insertions(+), 8 deletions(-) diff --git a/docs/5.typescript.md b/docs/5.typescript.md index e12e2e1b..a0a274c8 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -313,6 +313,8 @@ The build generates declarations from your module's own files, each with the pro - Every script in the runtime directory and in other directory entries, with TypeScript. - Every `.vue` file, with `@vue/language-core`, the same tooling that `vue-tsc` uses. +A tsconfig of your own that extends one in `.nuxt` and sets `paths` replaces the generated `paths`, `vue` among them. The build generates declarations with the generated entries that your `paths` leave out, and warns, as your type check doesn't resolve them. See [tsconfig `paths`](/docs/api/module-builder/upgrade-v2#tsconfig-paths) in the upgrade guide. + With TypeScript 7 installed next to the module's own TypeScript, the first two are several times faster. See [Declaration engines](/docs/api/module-builder/configuration#declaration-engines). The declaration program leaves out files under the module's `playground*`, `docs`, `test`, `tests`, `fixtures`, `example`, and `examples` directories. It also leaves out files that the tsconfig includes from outside the module root. The build still follows files that your module's sources import, wherever they are. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index e6814563..14728954 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -439,6 +439,12 @@ See [Checks on published paths](./3.develop-and-publish.md#checks-on-published-p These messages appear when the module doesn't have the tsconfigs of step 5. Either its tsconfig extends another app's `.nuxt/tsconfig.json`, such as a monorepo root's, or the build reads the nearest tsconfig above the module. Give the module a `tsconfig.json` in its own directory, as in [step 5](#step-5-switch-to-the-modules-own-tsconfigs). If one of the module's own tsconfigs can't be read, fix it, or generate the file it names before you run `prepare`. See [Monorepos](./5.typescript.md#monorepos). +### tsconfig `paths` + +The `paths` of a tsconfig replace those of the tsconfig that it extends. A tsconfig of your own that extends one in `.nuxt` and sets `paths` leaves out the entries that Nuxt generates, such as `#app`, `#imports`, and `vue` when it isn't in `devDependencies`. Your type check then doesn't resolve them, and types components as `any` without `vue`. The build generates declarations with the generated entries, and warns. + +Remove `paths` from that tsconfig, whether it is `tsconfig.json` extending `./.nuxt/tsconfig.json` or a tsconfig that `tsconfig.json` references in place of a generated one. Replace each of your aliases with a relative import, or with an entry in the `imports` field of `package.json`, as in [No tsconfig `paths` aliases](./5.typescript.md#no-tsconfig-paths-aliases). With source exports, add its `dist` path to `publishConfig.imports`. + ### Tests and config files Outside CI, `nuxt-module-build prepare` lists the TypeScript files that no tsconfig in `references` includes, with the number of files in each directory. `vue-tsc -b` doesn't type check them. These are usually tests outside `test/nuxt`, fixtures, and config files in the module root. diff --git a/src/build/build.ts b/src/build/build.ts index dcc11f59..8b33575a 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -12,7 +12,7 @@ import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts' import { loadOxc } from '../transpile/oxc.ts' import { EXCLUDE } from '../transpile/transpile-dir.ts' import type { ResolveExternal } from '../transpile/transpile-dir.ts' -import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, TsconfigError, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' +import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, packageName, replacedGeneratedPaths, restoredTsconfigPaths, TsconfigError, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' import type { TsconfigResolver } from '../transpile/tsconfig.ts' import { errors, warnings } from '../diagnostics.ts' import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' @@ -81,6 +81,7 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Pick const sources = [tsconfigs.replaced, ...['.nuxt/tsconfig.json', ...['node', 'app', 'server', 'shared'].map(part => `.nuxt/tsconfig.${part}.json`)].map(file => resolve(cwd, file))] warnings.NUXT_MB_C0301({ path: relative(cwd, tsconfigs.replaced), inside: isInside(cwd, tsconfigs.replaced), sources }, { method: 'info' }) } + reportReplacedPaths(cwd, tsconfigs) const directories: DirectoryEntry[] = [{ srcDir: resolve(cwd, 'src/runtime'), outDir: join(outDir, 'runtime'), ext: 'js' }, ...config.directories] const entries = bundledEntries(cwd, config) @@ -105,12 +106,33 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Pick isolatedDeclarations: config.isolatedDeclarations ?? hasIsolatedDeclarations(moduleTsconfig), selfPaths, declarationTsconfig: moduleTsconfig ? namedCachePath(cwd, `declarations-${createHash('sha256').update(outDir).digest('hex').slice(0, 12)}.json`) : false, - declarationPaths: declarationPaths({ ...selfPaths, ...tsconfigPaths(moduleTsconfig) }, cwd).paths, + declarationPaths: declarationPaths({ ...selfPaths, ...restoredTsconfigPaths(moduleTsconfig) }, cwd).paths, directoryPaths: { ...selfPaths, ...nuxtDir && { '#app/nuxt': [join(nuxtDir, 'dist/app/nuxt')] } }, generatedTypesHash: await hashGeneratedTypes(cwd), } } +/** + * Warns about the module's own tsconfigs whose `paths` replace generated entries that the + * module cannot resolve without them: aliases, and packages it does not install itself. + */ +function reportReplacedPaths(cwd: string, tsconfigs: TsconfigResolver) { + const replaced = [tsconfigs.root, ...tsconfigs.projects].flatMap((tsconfig) => { + const found = replacedGeneratedPaths(tsconfig) + const aliases = Object.keys(found?.paths ?? {}).filter((alias) => { + const name = packageName(alias) + return !name || !findPackageDir(name, cwd) + }) + return found && aliases.length ? [{ path: tsconfig!.path, generated: found.generated, aliases: aliases.sort((a, b) => Number(b === 'vue') - Number(a === 'vue')) }] : [] + }) + if (replaced.length) { + warnings.NUXT_MB_C0305({ + tsconfigs: replaced.map(({ path, generated, aliases }) => ({ path: relative(cwd, path), generated: relative(cwd, generated), aliases })), + sources: replaced.flatMap(({ path, generated }) => [path, generated]), + }) + } +} + /** * Runs `build:before` hooks, checks the module's imports, empties the output directory unless * `keepOutput` is set, and writes what declaration generation reads. diff --git a/src/diagnostics.ts b/src/diagnostics.ts index b8c10864..0a3ba1b4 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -13,6 +13,10 @@ function list(values: string[]) { return [...new Set(values)].map(value => `\`${value}\``).join(', ') } +function someOf(values: string[], shown = 4) { + return values.length > shown + 1 ? `${list(values.slice(0, shown))} and ${values.length - shown} more` : list(values) +} + const UNPUBLISHABLE = 'TypeScript sources or paths that `files` leaves out' /** The upgrade guide as released with this version, which the `docs` anchors of diagnostics point into. */ @@ -266,6 +270,14 @@ export const warningCodes = { fix: 'Reference a tsconfig that includes them, such as a `tsconfig.test.json` for tests and config files, or add them to the `exclude` of `tsconfig.json`.', docs: '#tests-and-config-files', }, + NUXT_MB_C0305: { + why: (p: { tsconfigs: Array<{ path: string, generated: string, aliases: string[] }> }): string => [ + `These tsconfigs set \`paths\`, which replace the \`paths\` of the generated tsconfig that they extend, so the module's own type check does not resolve the entries they leave out${p.tsconfigs.some(({ aliases }) => aliases.includes('vue')) ? ', and types components as `any`, as `vue` is one of them' : ''}. The declarations are generated with these entries.`, + ...p.tsconfigs.map(({ path, generated, aliases }) => ` - \`${path}\` leaves out ${someOf(aliases)} of \`${generated}\``), + ].join('\n'), + fix: (p: { tsconfigs: Array<{ path: string }> }): string => `Remove \`paths\` from ${list(p.tsconfigs.map(({ path }) => path))}. Replace each of its aliases with a relative import, or with an entry in the \`imports\` field of \`package.json\`, with its \`dist\` path in \`publishConfig.imports\`.`, + docs: '#tsconfig-paths', + }, NUXT_MB_C0404: { why: (p: { engine: string, reason: string }): string => `The \`${p.engine}\` declaration engine cannot be used: ${p.reason}. Declarations are generated with the JavaScript API of the module's own TypeScript instead.`, fix: (p: { engine: string }): string => `Nothing to change for this build. To generate declarations with \`${p.engine}\`, install a version of it that runs here, or set \`declarations.engine\` to \`typescript\` to skip it.`, diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 5644dac3..4aa2d330 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -15,6 +15,8 @@ export interface TsconfigResolver { root: TsConfigResult | undefined /** The tsconfig a source file is compiled with. */ resolve: (file: string) => TsConfigResult | undefined + /** The projects that `root` references, directly or through other projects. */ + projects: TsConfigResult[] /** The tsconfig found above `dir` when it took its generated types from another app's `.nuxt`, which `.nuxt/tsconfig.json` replaces in `root`. */ replaced?: string } @@ -44,6 +46,7 @@ export async function createTsconfigResolver(dir: string): Promise projects.find(({ matches }) => matches(file.endsWith('.vue') ? `${file}.ts` : file))?.project ?? root, + projects: projects.map(({ project }) => project), ...replaced && { replaced }, } } @@ -312,6 +315,47 @@ export function tsconfigPaths(tsconfig: TsConfigResult | undefined): Record [alias, matchPath(alias)])) : {} } +/** The generated tsconfig in a `.nuxt` that `tsconfig` extends, directly or through other tsconfigs, and the entries of its `paths` that the `paths` of `tsconfig` replace, made absolute. */ +export interface ReplacedPaths { + generated: string + paths: Record +} + +/** See {@link ReplacedPaths}. `undefined` when `tsconfig` is generated itself, extends none, or keeps every entry. */ +export function replacedGeneratedPaths(tsconfig: TsConfigResult | undefined): ReplacedPaths | undefined { + if (!tsconfig || NUXT_BUILD_DIR_RE.test(tsconfig.path)) { + return + } + const generated = generatedBase(tsconfig.path, new Set([tsconfig.path])) + if (!generated) { + return + } + const own = tsconfigPaths(tsconfig) + const paths = Object.fromEntries(Object.entries(tsconfigPaths({ path: generated, config: parseTsconfig(generated) })).filter(([alias]) => !(alias in own))) + return Object.keys(paths).length ? { generated, paths } : undefined +} + +function generatedBase(file: string, seen: Set): string | undefined { + const { ts } = loadTypescript() + const raw = ts.readConfigFile(file, ts.sys.readFile).config as RawTsconfig | undefined + for (const target of [raw?.extends ?? []].flat().reverse()) { + const resolved = resolveExtends(ts, target, dirname(file)) + if (!resolved || seen.has(resolved)) { + continue + } + seen.add(resolved) + const found = NUXT_BUILD_DIR_RE.test(resolved) ? resolved : generatedBase(resolved, seen) + if (found) { + return found + } + } +} + +/** The tsconfig's `paths` made absolute, with the generated entries that they replace (see {@link replacedGeneratedPaths}) under them. */ +export function restoredTsconfigPaths(tsconfig: TsConfigResult | undefined): Record { + return { ...replacedGeneratedPaths(tsconfig)?.paths, ...tsconfigPaths(tsconfig) } +} + const BUILD_ALIAS_RE = /^#(?:build|internal)(?:\/|$)/ const SERVER_ROUTES_ALIAS = '#build/server-routes' const NUXT_BUILD_DIR_RE = /[\\/]\.nuxt(?:[\\/]|$)/ @@ -390,12 +434,12 @@ async function writeAtomic(file: string, contents: string) { } /** - * The {@link declarationPaths} of the `paths` of `tsconfig` plus `paths`, once the files they + * The {@link declarationPaths} of the {@link restoredTsconfigPaths} of `tsconfig` plus `paths`, once the files they * rely on are written: the server routes stub, and the `ambient` file that declares each alias * left out as a module. */ export async function writeDeclarationPaths(cwd: string, tsconfig: TsConfigResult | undefined, paths: Record): Promise<{ paths: Record, ambient?: string }> { - const declaration = declarationPaths({ ...tsconfigPaths(tsconfig), ...paths }, cwd) + const declaration = declarationPaths({ ...restoredTsconfigPaths(tsconfig), ...paths }, cwd) await writeServerRoutesStub(cwd) return { paths: declaration.paths, @@ -470,7 +514,7 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu /** * Writes a tsconfig extending `tsconfig`, for tools that take a tsconfig file. Its `paths` - * are the tsconfig's plus `paths`, less what {@link declarationPaths} drops; the aliases + * are the tsconfig's {@link restoredTsconfigPaths} plus `paths`, less what {@link declarationPaths} drops; the aliases * that are not followed get an ambient `declare module` through `types`. Declarations are * inferred, so `isolatedDeclarations` is off. The files are listed rather than inherited, * less those of a playground (see {@link projectFiles}). Each project in `references` is diff --git a/test/builder.spec.ts b/test/builder.spec.ts index 3b192e7f..a83b1a16 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -1,4 +1,6 @@ +import { createHash } from 'node:crypto' import { readdir, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { join } from 'pathe' import { beforeAll, describe, expect, it } from 'vitest' @@ -14,6 +16,20 @@ const REFERENCES = (node: string, server = './.nuxt/tsconfig.server.json') => JS }) const FIELDS = `\nclass Fields { value!: string }\nexport const ownsField: boolean = Object.hasOwn(new Fields(), 'value')\n` const store = (name: string) => `node_modules/.pnpm/${name}@1.0.0/node_modules/${name}` +const COMPONENTS = { + 'src/runtime/components/ErrorState.vue': `\n\n\n`, + 'src/runtime/components/RowActions.vue': `\n\n\n`, + 'src/runtime/components/WithEmits.vue': `\n\n\n`, + 'src/runtime/components/WithSlots.vue': `\n\n\n`, + 'src/runtime/components/WithModel.vue': `\n\n\n`, + 'src/runtime/components/WithExpose.vue': `\n\n\n`, + 'src/runtime/components/index.ts': `import ErrorState from './ErrorState.vue'\n\nexport { default as TestMe } from './TestMe.vue'\nexport const errorState = ErrorState\n`, +} +const NO_VUE_DIR = join(tmpdir(), `module-builder-without-vue-${createHash('sha256').update(repoRoot).digest('hex').slice(0, 8)}`) +const LEGACY_PATHS = (paths: Record) => JSON.stringify({ extends: './.nuxt/tsconfig.json', compilerOptions: { paths }, exclude: ['dist', 'node_modules', 'playground'] }) +const MY_PATHS = { '#my/*': ['./src/runtime/*'] } +const ANY_COMPONENT_RE = /declare const __VLS_(?:export|base): any;/ +const componentDeclarations = async (dir: string) => Object.fromEntries(await Promise.all(['ErrorState', 'RowActions', 'TestMe', 'TestMeSetup', 'WithEmits', 'WithSlots', 'WithModel', 'WithExpose'].map(async name => [name, await read(dir, `dist/runtime/components/${name}.d.vue.ts`)] as const))) const sizeRows = (output: string) => [...output.matchAll(/(dist\/(?:module\.mjs|runtime\/))\s[^\n]*types/g)].map(match => match[1]).sort() const dirs: Record = {} @@ -256,7 +272,19 @@ export default { files: { 'tsconfig.json': JSON.stringify({ extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground'] }) }, }) + const withoutVue = (name: string, options: Parameters[1] = {}) => fixture(join(NO_VUE_DIR, name), { config: PLUGIN, ...options, files: { ...COMPONENTS, ...options.files } }) + dirs.legacyPaths = await withoutVue('legacy-paths', { files: { 'tsconfig.json': LEGACY_PATHS(MY_PATHS) } }) + dirs.ownVue = await withoutVue('own-vue', { files: { 'tsconfig.json': LEGACY_PATHS({ vue: ['./src/runtime/vue.d.ts'] }), 'src/runtime/vue.d.ts': 'export declare function defineComponent(options: unknown): \'from the module\'\n' } }) + dirs.partPaths = await withoutVue('part-paths', { + files: { + 'tsconfig.json': REFERENCES('./.nuxt/tsconfig.node.json').replace('./.nuxt/tsconfig.app.json', './tsconfig.app.json'), + 'tsconfig.app.json': JSON.stringify({ extends: './.nuxt/tsconfig.app.json', compilerOptions: { tsBuildInfoFile: './.nuxt/tsconfig.app.tsbuildinfo', paths: MY_PATHS } }), + }, + }) + dirs.rootPaths = await withoutVue('root-paths', { files: { 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json')), compilerOptions: { paths: MY_PATHS } }) } }) + await Promise.all([ + ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths'].map(name => step(name, tsdown(dirs[name]!))), step('compose', tsdown(dirs.compose)), step('packageImports', tsdown(dirs.packageImports)), step('warnings', tsdown(dirs.warnings)) @@ -526,3 +554,41 @@ describe('with a root tsconfig that only lists references', () => { expect(await read(dirs.nested!, '.nuxt/module-builder/declarations/src/lib/two.d.ts')).toContain('label: string;') }) }) + +describe('a module that does not install `vue`', () => { + const expectTyped = async (dir: string) => { + const declarations = await componentDeclarations(dir) + expect(Object.entries(declarations).filter(([, text]) => ANY_COMPONENT_RE.test(text)).map(([name]) => name)).toEqual([]) + expect(declarations.ErrorState).toContain('description?: string;') + expect(declarations.RowActions).toContain('row: R;') + expect(await read(dir, 'dist/runtime/components/index.d.ts')).toMatch(/^export declare const errorState: import\("vue"\)\.DefineComponent<\{\n {4}description\?: string;/m) + } + + it('should declare its components with the types of `vue` when its tsconfig extends `.nuxt/tsconfig.json` and sets `paths`, and warn about the entries they replace', async () => { + const output = expectBuilt('legacyPaths') + await expectTyped(dirs.legacyPaths!) + expect(output).toContain('[NUXT_MB_C0305]') + expect(output).toMatch(/- `tsconfig\.json` leaves out `vue`, .* of `\.nuxt\/tsconfig\.json`/) + expect(output).toContain(`${GUIDE_URL}#tsconfig-paths`) + }) + + it('should declare its components with the types of `vue` when a referenced tsconfig of its own sets `paths`, and warn about the entries they replace', async () => { + const output = expectBuilt('partPaths') + await expectTyped(dirs.partPaths!) + expect(output).toMatch(/- `tsconfig\.app\.json` leaves out `vue`, .* of `\.nuxt\/tsconfig\.app\.json`/) + expect(output).not.toContain('NUXT_MB_B0101') + }) + + it('should not warn about `paths` in a root tsconfig that only lists references, which replace no generated entries', async () => { + const output = expectBuilt('rootPaths') + await expectTyped(dirs.rootPaths!) + expect(output).not.toContain('NUXT_MB_C0305') + }) + + it('should keep the module\'s own `paths` entry for a package that a generated tsconfig maps too', async () => { + const output = expectBuilt('ownVue') + expect(await read(dirs.ownVue!, 'dist/runtime/components/ErrorState.d.vue.ts')).toContain('declare const __VLS_export: "from the module";') + expect(output).toMatch(/- `tsconfig\.json` leaves out `@nuxt\/devtools`/) + expect(output).not.toMatch(/leaves out `vue`/) + }) +}) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 9a23864a..e2b883a4 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -22,7 +22,7 @@ import { unchangedOutputs } from '../src/tsdown/unchanged.ts' import type { Rolldown, UserConfig } from 'tsdown' import { exec } from 'tinyexec' import { bundledPackages, runtimeExternals } from '../src/tsdown/externals.ts' -import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, packageName, rootTsconfig, tsconfigPaths, typeResolutionFs, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' +import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, packageName, replacedGeneratedPaths, rootTsconfig, tsconfigPaths, typeResolutionFs, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' import { transformCss } from '../src/transpile/stylesheets.ts' import { contentCache } from '../src/transpile/cache.ts' import { createDeclarationProgram, declarationDiagnosticClass, declarationError, REMAPPED_CODES, restoreImports } from '../src/transpile/declarations.ts' @@ -1426,6 +1426,27 @@ describe('resolveOutDir', () => { }) }) +describe('replacedGeneratedPaths', () => { + it('should list the generated entries that the module\'s own `paths` replace, through the tsconfigs that it extends, and none for a generated tsconfig or one without `paths`', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'module-builder-replaced-')) + onTestFinished(() => rm(cwd, { recursive: true, force: true })) + await mkdir(join(cwd, '.nuxt')) + const generated = join(cwd, '.nuxt/tsconfig.app.json') + await writeFile(generated, JSON.stringify({ compilerOptions: { paths: { 'vue': ['../node_modules/vue'], '#app': ['../node_modules/nuxt/dist/app'], '#my/*': ['../generated/*'] } } })) + const tsconfig = async (name: string, config: object) => { + await writeFile(join(cwd, name), JSON.stringify(config)) + return { path: join(cwd, name), config: parseTsconfig(join(cwd, name)) } + } + await tsconfig('tsconfig.base.json', { extends: './.nuxt/tsconfig.app.json', compilerOptions: { paths: { '#my/*': ['./src/*'] } } }) + expect(replacedGeneratedPaths(await tsconfig('tsconfig.app.json', { extends: './tsconfig.base.json', compilerOptions: { strict: true } }))).toEqual({ + generated, + paths: { 'vue': [join(cwd, 'node_modules/vue')], '#app': [join(cwd, 'node_modules/nuxt/dist/app')] }, + }) + expect(replacedGeneratedPaths(await tsconfig('tsconfig.plain.json', { extends: './.nuxt/tsconfig.app.json', compilerOptions: { strict: true } }))).toBeUndefined() + expect(replacedGeneratedPaths({ path: generated, config: parseTsconfig(generated) })).toBeUndefined() + }) +}) + describe('createTsconfigResolver', () => { it('should fail with a diagnostic naming the module\'s tsconfig, or a project it references, that cannot be read', async () => { const root = await mkdtemp(join(tmpdir(), 'module-builder-unreadable-')) diff --git a/test/utils.ts b/test/utils.ts index 84b0e410..b2fe4429 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -111,11 +111,11 @@ export interface FixtureOptions { const DEFAULT_CONFIG = `export default {\n plugins: [builder({ entries: ['./src/utils'] })],\n}\n` /** - * Copies `example` to `dir` under the repository, without `dist`, with `package.json` as it is + * Copies `example` to `dir`, relative to the repository unless absolute, without `dist`, with `package.json` as it is * published and a tsdown config that builds it with `builder()`. */ export async function fixture(dir: string, { from = exampleDir, config = DEFAULT_CONFIG, module, files = {}, remove = [], pkg, paths, links = {} }: FixtureOptions = {}): Promise { - const root = join(repoRoot, dir) + const root = resolve(repoRoot, dir) await rm(root, { recursive: true, force: true }) await mkdir(dirname(root), { recursive: true }) await cp(from, root, { recursive: true }) From cd8a5433c0c9deb6fb0230f1f0b3600dfa506793 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 22:42:16 +0000 Subject: [PATCH 3/8] fix: prepare `.nuxt` again when its `paths` point at missing packages --- docs/5.typescript.md | 2 +- docs/upgrade-v2.md | 2 +- src/diagnostics.ts | 5 +++++ src/transpile/tsconfig.ts | 33 ++++++++++++++++++++++++++++++++- src/tsdown/setup.ts | 9 ++++++++- test/builder.spec.ts | 13 +++++++++++-- test/unit.spec.ts | 23 ++++++++++++++++++++++- 7 files changed, 80 insertions(+), 7 deletions(-) diff --git a/docs/5.typescript.md b/docs/5.typescript.md index a0a274c8..c81e2083 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -319,7 +319,7 @@ With TypeScript 7 installed next to the module's own TypeScript, the first two a The declaration program leaves out files under the module's `playground*`, `docs`, `test`, `tests`, `fixtures`, `example`, and `examples` directories. It also leaves out files that the tsconfig includes from outside the module root. The build still follows files that your module's sources import, wherever they are. -If `.nuxt` is out of date, the declarations are too. Run `nuxt-module-build prepare` again after you change what the module adds to the types. +If `.nuxt` is out of date, the declarations are too. Run `nuxt-module-build prepare` again after you change what the module adds to the types, and after you update dependencies. When the tsconfigs in `.nuxt` map a package into a directory that no longer exists, the build runs `nuxt-module-build prepare` first. Declarations are kept in `node_modules/.cache/transpile-dir` and reused while none of the files they were generated from has changed, so building an unchanged module again does no type work. Remove that directory to generate them all again. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 14728954..c0aebe77 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -368,7 +368,7 @@ The build empties the output directory before it writes to it, and `tsdown --wat ### Preparing `.nuxt` -The build generates declarations with the tsconfigs in `.nuxt`, so it runs `nuxt-module-build prepare` first when `.nuxt` is missing. Run `nuxt-module-build prepare` first in your `dev:prepare` script instead, as in [step 7](#step-7-update-the-scripts). +The build generates declarations with the tsconfigs in `.nuxt`, so it runs `nuxt-module-build prepare` first when `.nuxt` is missing. It does the same when the tsconfigs in `.nuxt` map a package into a directory that no longer exists, as after a dependency update. Run `nuxt-module-build prepare` first in your `dev:prepare` script instead, as in [step 7](#step-7-update-the-scripts), and again after you update dependencies. The `.nuxt` that the build prepares can leave out the declarations that the module's own type check reads. Run `nuxt-module-build prepare` yourself before `vue-tsc -b --noEmit`. diff --git a/src/diagnostics.ts b/src/diagnostics.ts index 0a3ba1b4..3277b0a7 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -226,6 +226,11 @@ export const warningCodes = { fix: 'Add `nuxt-module-build prepare` to the module\'s `dev:prepare` script to skip this step.', docs: '#preparing-nuxt', }, + NUXT_MB_B0102: { + why: (p: { aliases: string[] }): string => `\`.nuxt\` is out of date: its tsconfigs map ${someOf(p.aliases)} into packages that are not installed. Running \`nuxt-module-build prepare\` first.`, + fix: 'Run `nuxt-module-build prepare` again after you update dependencies, to skip this step and to type check the module with the installed packages.', + docs: '#preparing-nuxt', + }, NUXT_MB_B0202: { why: (p: { setting: string }): string => `The declarations of the bundled entries are generated with oxc, as ${p.setting} selects, which requires an explicit type annotation on every exported value, and some have none.`, fix: 'Give each export that an error names an explicit type. Write the module entry as:\n\n const module: NuxtModule = defineNuxtModule({ /* ... */ })\n export default module\n\nrather than `export default defineNuxtModule({ /* ... */ })`.', diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 4aa2d330..f548d965 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from 'node:crypto' -import { existsSync } from 'node:fs' +import { existsSync, readFileSync } from 'node:fs' import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { createFilesMatcher, createPathsMatcher, getTsconfig, parseTsconfig } from 'get-tsconfig' import type { TsConfigResult } from 'get-tsconfig' @@ -356,6 +356,37 @@ export function restoredTsconfigPaths(tsconfig: TsConfigResult | undefined): Rec return { ...replacedGeneratedPaths(tsconfig)?.paths, ...tsconfigPaths(tsconfig) } } +const PACKAGE_DIR_RE = /^(.*[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^.\\/][^\\/]*)/ + +/** + * The aliases that the `paths` of the tsconfigs in `dir/.nuxt` map into a package directory that + * does not exist, as after an update of the dependencies since `.nuxt` was generated, with the + * tsconfigs that map them. + */ +export function missingPathPackages(dir: string): { aliases: string[], tsconfigs: string[] } { + const buildDir = join(dir, '.nuxt') + const aliases = new Set() + const tsconfigs = new Set() + for (const name of ['tsconfig.json', ...['app', 'node', 'server', 'shared'].map(part => `tsconfig.${part}.json`)]) { + const file = join(buildDir, name) + let paths: Record | undefined + try { + paths = JSON.parse(readFileSync(file, 'utf8')).compilerOptions?.paths + } + catch { + continue + } + for (const [alias, targets] of Object.entries(paths ?? {})) { + const packageDir = targets.map(target => resolve(buildDir, target).match(PACKAGE_DIR_RE)?.[1]).find(Boolean) + if (packageDir && !existsSync(packageDir)) { + aliases.add(alias) + tsconfigs.add(file) + } + } + } + return { aliases: [...aliases], tsconfigs: [...tsconfigs] } +} + const BUILD_ALIAS_RE = /^#(?:build|internal)(?:\/|$)/ const SERVER_ROUTES_ALIAS = '#build/server-routes' const NUXT_BUILD_DIR_RE = /[\\/]\.nuxt(?:[\\/]|$)/ diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index b79ccd4b..85b63543 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -16,6 +16,7 @@ import { prepareModule } from '../commands/prepare.ts' import { errors, unwrapBuildError, useBuildLogger, warnings } from '../diagnostics.ts' import { loadOxc } from '../transpile/oxc.ts' import { transpileDir } from '../transpile/transpile-dir.ts' +import { missingPathPackages } from '../transpile/tsconfig.ts' import { findUp, readPackageJson, realpath } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { bundledPackages, externalDependencyDeclarations, runtimeExternals } from './externals.ts' @@ -90,8 +91,14 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt const outDir = resolveOutDir(cwd, outDirOption, inline.outDir === undefined && config.outDir !== undefined ? `outDir: '${outDirOption}'` : `--outDir ${outDirOption}`) const buildConfig = loadConfig ? await loadConfig(cwd, pkg, outDir) : resolveModuleOptions(cwd, pkg, outDir, options) - if (!existsSync(resolve(cwd, '.nuxt/tsconfig.json'))) { + const stale = existsSync(resolve(cwd, '.nuxt/tsconfig.json')) ? missingPathPackages(cwd) : undefined + if (!stale) { warnings.NUXT_MB_B0101(undefined, { method: 'info' }) + } + else if (stale.aliases.length) { + warnings.NUXT_MB_B0102({ aliases: stale.aliases, sources: stale.tsconfigs }, { method: 'info' }) + } + if (!stale || stale.aliases.length) { await prepareModule(cwd, { config: buildConfig, outDir, pkg }, { declarations: false }) } diff --git a/test/builder.spec.ts b/test/builder.spec.ts index a83b1a16..eb9b39ee 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -282,9 +282,11 @@ export default { }, }) dirs.rootPaths = await withoutVue('root-paths', { files: { 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json')), compilerOptions: { paths: MY_PATHS } }) } }) + const staleVue = (source: string) => source.replace(/\.pnpm\/vue@[^/]+\//g, '.pnpm/vue@0.0.0/') + dirs.stale = await withoutVue('stale', { files: Object.fromEntries(['', '.app', '.node', '.server', '.shared'].map(part => [`.nuxt/tsconfig${part}.json`, staleVue])) }) await Promise.all([ - ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths'].map(name => step(name, tsdown(dirs[name]!))), + ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths', 'stale'].map(name => step(name, tsdown(dirs[name]!))), step('compose', tsdown(dirs.compose)), step('packageImports', tsdown(dirs.packageImports)), step('warnings', tsdown(dirs.warnings)) @@ -576,7 +578,7 @@ describe('a module that does not install `vue`', () => { const output = expectBuilt('partPaths') await expectTyped(dirs.partPaths!) expect(output).toMatch(/- `tsconfig\.app\.json` leaves out `vue`, .* of `\.nuxt\/tsconfig\.app\.json`/) - expect(output).not.toContain('NUXT_MB_B0101') + expect(output).not.toMatch(/NUXT_MB_B010[12]/) }) it('should not warn about `paths` in a root tsconfig that only lists references, which replace no generated entries', async () => { @@ -591,4 +593,11 @@ describe('a module that does not install `vue`', () => { expect(output).toMatch(/- `tsconfig\.json` leaves out `@nuxt\/devtools`/) expect(output).not.toMatch(/leaves out `vue`/) }) + + it('should prepare `.nuxt` again when its tsconfigs map a package into a directory that no longer exists', async () => { + const output = expectBuilt('stale') + expect(output).toMatch(/\[NUXT_MB_B0102\] `\.nuxt` is out of date: its tsconfigs map `vue` into packages that are not installed/) + await expectTyped(dirs.stale!) + expect(await read(dirs.stale!, '.nuxt/tsconfig.app.json')).not.toContain('vue@0.0.0') + }) }) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index e2b883a4..4d6a3fc2 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -22,7 +22,7 @@ import { unchangedOutputs } from '../src/tsdown/unchanged.ts' import type { Rolldown, UserConfig } from 'tsdown' import { exec } from 'tinyexec' import { bundledPackages, runtimeExternals } from '../src/tsdown/externals.ts' -import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, packageName, replacedGeneratedPaths, rootTsconfig, tsconfigPaths, typeResolutionFs, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' +import { SERVER_ROUTES_STUB, createTsconfigResolver, declarationPaths, missingPathPackages, packageName, replacedGeneratedPaths, rootTsconfig, tsconfigPaths, typeResolutionFs, writeDerivedTsconfig, writeServerRoutesStub } from '../src/transpile/tsconfig.ts' import { transformCss } from '../src/transpile/stylesheets.ts' import { contentCache } from '../src/transpile/cache.ts' import { createDeclarationProgram, declarationDiagnosticClass, declarationError, REMAPPED_CODES, restoreImports } from '../src/transpile/declarations.ts' @@ -1426,6 +1426,27 @@ describe('resolveOutDir', () => { }) }) +describe('missingPathPackages', () => { + it('should list the aliases that `.nuxt` maps into a package directory that does not exist, and not those into a file of an installed package or outside a package', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'module-builder-stale-')) + onTestFinished(() => rm(cwd, { recursive: true, force: true })) + await mkdir(join(cwd, '.nuxt')) + await mkdir(join(cwd, 'node_modules/.pnpm/nuxt@4.0.0/node_modules/nuxt'), { recursive: true }) + await mkdir(join(cwd, 'node_modules/.cache'), { recursive: true }) + const paths = { + 'vue-demi': ['../node_modules/.pnpm/nuxt@4.0.0/node_modules/nuxt/dist/app/compat/vue-demi'], + 'vue': ['../node_modules/.pnpm/vue@3.0.0/node_modules/vue'], + '@unhead/vue': ['../node_modules/.pnpm/@unhead+vue@2.0.0/node_modules/@unhead/vue'], + '#app-manifest': ['../node_modules/.cache/nuxt/manifest'], + '#shared': ['../shared'], + '#build/*': ['./*'], + } + await writeFile(join(cwd, '.nuxt/tsconfig.json'), JSON.stringify({ compilerOptions: { paths } })) + await writeFile(join(cwd, '.nuxt/tsconfig.app.json'), JSON.stringify({ compilerOptions: { paths: { 'vue-demi': paths['vue-demi'] } } })) + expect(missingPathPackages(cwd)).toEqual({ aliases: ['vue', '@unhead/vue'], tsconfigs: [join(cwd, '.nuxt/tsconfig.json')] }) + }) +}) + describe('replacedGeneratedPaths', () => { it('should list the generated entries that the module\'s own `paths` replace, through the tsconfigs that it extends, and none for a generated tsconfig or one without `paths`', async () => { const cwd = await mkdtemp(join(tmpdir(), 'module-builder-replaced-')) From 27676a40e10897967f3cec5c497ad675d1553d25 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 22:42:20 +0000 Subject: [PATCH 4/8] feat: fail when `vue` does not resolve from a non-generic component --- docs/5.typescript.md | 2 ++ docs/upgrade-v2.md | 1 + src/build/build.ts | 23 ++++++++++++++++- src/diagnostics.ts | 6 +++++ src/transpile/tsconfig.ts | 54 ++++++++++++++++++++++++++++++++++++++- test/builder.spec.ts | 12 ++++++++- 6 files changed, 95 insertions(+), 3 deletions(-) diff --git a/docs/5.typescript.md b/docs/5.typescript.md index c81e2083..15296f3c 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -313,6 +313,8 @@ The build generates declarations from your module's own files, each with the pro - Every script in the runtime directory and in other directory entries, with TypeScript. - Every `.vue` file, with `@vue/language-core`, the same tooling that `vue-tsc` uses. +The declaration of a component without a `generic` script setup is inferred from the types of `vue`. The tsconfigs in `.nuxt` map `vue` in `paths`, so a module whose tsconfig neither extends nor references them needs `vue` in `devDependencies`. + A tsconfig of your own that extends one in `.nuxt` and sets `paths` replaces the generated `paths`, `vue` among them. The build generates declarations with the generated entries that your `paths` leave out, and warns, as your type check doesn't resolve them. See [tsconfig `paths`](/docs/api/module-builder/upgrade-v2#tsconfig-paths) in the upgrade guide. With TypeScript 7 installed next to the module's own TypeScript, the first two are several times faster. See [Declaration engines](/docs/api/module-builder/configuration#declaration-engines). diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index c0aebe77..79e5eb52 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -378,6 +378,7 @@ The build generates declarations with TypeScript, using the tsconfig project tha - An export whose inferred type can't be named (TS2742, TS2883, or TS4023) needs a type annotation. See [Portability errors](#portability-errors). - If `.nuxt` is out of date, run `nuxt-module-build prepare` and build again. +- A component without a `generic` script setup is declared with the types of `vue`, so the build fails when `vue` doesn't resolve from it. Add `vue` to `devDependencies`, or make the tsconfig that includes the component extend or reference the tsconfigs in `.nuxt`, which map `vue` in `paths`. - Syntax errors, and files for which no declaration can be emitted, fail the build too. The build doesn't type check otherwise, so your own type check reports every other type error. See [Declarations](./5.typescript.md#declarations). diff --git a/src/build/build.ts b/src/build/build.ts index 8b33575a..1c2b5461 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -12,7 +12,7 @@ import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts' import { loadOxc } from '../transpile/oxc.ts' import { EXCLUDE } from '../transpile/transpile-dir.ts' import type { ResolveExternal } from '../transpile/transpile-dir.ts' -import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, packageName, replacedGeneratedPaths, restoredTsconfigPaths, TsconfigError, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' +import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, packageName, replacedGeneratedPaths, restoredTsconfigPaths, TsconfigError, unresolvedVueLibrary, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' import type { TsconfigResolver } from '../transpile/tsconfig.ts' import { errors, warnings } from '../diagnostics.ts' import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' @@ -146,6 +146,7 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput } await writeServerRoutesStub(cwd) + await assertResolvableVueLibrary(plan) if (plan.moduleTsconfig && plan.declarationTsconfig) { const imports = plan.moduleProject ? await writeDependencyImports(cwd, plan.rootTsconfig) : undefined await writeDerivedTsconfig(cwd, plan.moduleTsconfig, plan.selfPaths, { file: plan.declarationTsconfig, imports }) @@ -153,6 +154,26 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput plan.prepared = analyseSources(plan) } +const SCRIPT_TAG_RE = /"']|"[^"]*"|'[^']*')*>/gi + +/** + * Fails when the library that the generated code of a single-file component imports does not + * resolve from it, for each component whose declaration is inferred from that library: every + * component but one with a `generic` script setup, whose declaration spells out its type. + */ +async function assertResolvableVueLibrary(plan: BuildPlan) { + const { cwd, rootTsconfig, directories } = plan + const components = directories.flatMap(directory => globSync(['**/*.vue'], { cwd: directory.srcDir, ignore: EXCLUDE, absolute: true, onlyFiles: true }).map(file => normalize(file))) + const inferred = components.filter(file => ![...readFileSync(file, 'utf8').matchAll(SCRIPT_TAG_RE)].some(([tag]) => /\ssetup\b/.test(tag) && /\sgeneric\s*=/.test(tag))) + if (!rootTsconfig || !inferred.length) { + return + } + const unresolved = unresolvedVueLibrary(await writeDerivedTsconfig(cwd, rootTsconfig, plan.directoryPaths, { vue: true }), inferred) + if (unresolved.length) { + throw errors.NUXT_MB_B0206({ lib: unresolved[0]!.lib, files: unresolved.map(({ file }) => relative(cwd, file)), sources: unresolved.map(({ file }) => file) }) + } +} + /** * Finds the bundled sources and the runtime files whose JSX is compiled, for the build about * to start. Rebuilds under watch call it again, as files may have been added. diff --git a/src/diagnostics.ts b/src/diagnostics.ts index 3277b0a7..dac60779 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -82,6 +82,12 @@ export const errorCodes = { docs: false, }, + NUXT_MB_B0206: { + why: (p: { lib: string, files: string[] }): string => `\`${p.lib}\` does not resolve from these components with the tsconfig that their declarations are generated with, so each would be declared as \`any\`: ${list(p.files)}.`, + fix: (p: { lib: string }): string => `Add \`${p.lib}\` to \`devDependencies\`, or make the tsconfig that includes them extend or reference the tsconfigs in \`.nuxt\`, which map it in \`paths\`.`, + docs: '#declaration-errors', + }, + NUXT_MB_C0001: { why: (p: { options: Array<{ option: string, reason: string }> }): string => [ '`builder()` sets these tsdown options itself, and the tsdown config sets them too:', diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index f548d965..45f91667 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync } from 'node:fs' import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { createFilesMatcher, createPathsMatcher, getTsconfig, parseTsconfig } from 'get-tsconfig' import type { TsConfigResult } from 'get-tsconfig' -import { dirname, join, relative, resolve } from 'pathe' +import { dirname, join, normalize, relative, resolve } from 'pathe' import type ts from 'typescript' import { findPackageDir, findUp, getOrCreate, isInside, NODE_MODULES_RE } from '../utils.ts' @@ -356,6 +356,58 @@ export function restoredTsconfigPaths(tsconfig: TsConfigResult | undefined): Rec return { ...replacedGeneratedPaths(tsconfig)?.paths, ...tsconfigPaths(tsconfig) } } +/** + * The `.vue` files among `files` from which the library that their generated code imports, + * `vueCompilerOptions.lib` or else `vue`, does not resolve. Each is resolved with the options of + * the project of `tsconfig` that a declaration program over it compiles the file with: the + * first that lists it, or else the first. + */ +export function unresolvedVueLibrary(tsconfig: string, files: string[]): Array<{ file: string, lib: string }> { + const { ts } = loadTypescript() + const projects: Array<{ path: string, options: ts.CompilerOptions, fileNames: Set, lib: string }> = [] + const seen = new Set() + const collect = (path: string) => { + if (seen.has(path)) { + return + } + seen.add(path) + const parsed = parseProject(ts, path, true) + if (parsed && !parsed.fileNames.length && parsed.projectReferences?.length) { + for (const reference of parsed.projectReferences) { + collect(normalize(ts.resolveProjectReferencePath(reference))) + } + } + else if (parsed) { + projects.push({ path, options: parsed.options, fileNames: new Set(parsed.fileNames.map(file => normalize(file))), lib: vueLibrary(ts, path, new Set()) ?? 'vue' }) + } + } + collect(normalize(tsconfig)) + const resolved = new Map() + return files.flatMap((file) => { + const project = projects.find(({ fileNames }) => fileNames.has(normalize(file))) ?? projects[0] + if (!project) { + return [] + } + const found = getOrCreate(resolved, `${project.path}\0${dirname(file)}`, () => !!ts.resolveModuleName(project.lib, file, project.options, ts.sys).resolvedModule) + return found ? [] : [{ file, lib: project.lib }] + }) +} + +function vueLibrary(ts: typeof import('typescript'), file: string, seen: Set): string | undefined { + seen.add(file) + const raw = ts.readConfigFile(file, ts.sys.readFile).config as (RawTsconfig & { vueCompilerOptions?: { lib?: string } }) | undefined + if (typeof raw?.vueCompilerOptions?.lib === 'string') { + return raw.vueCompilerOptions.lib + } + for (const target of [raw?.extends ?? []].flat().reverse()) { + const resolved = resolveExtends(ts, target, dirname(file)) + const lib = resolved && !seen.has(resolved) ? vueLibrary(ts, resolved, seen) : undefined + if (lib) { + return lib + } + } +} + const PACKAGE_DIR_RE = /^(.*[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^.\\/][^\\/]*)/ /** diff --git a/test/builder.spec.ts b/test/builder.spec.ts index eb9b39ee..dfd30198 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -284,9 +284,10 @@ export default { dirs.rootPaths = await withoutVue('root-paths', { files: { 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json')), compilerOptions: { paths: MY_PATHS } }) } }) const staleVue = (source: string) => source.replace(/\.pnpm\/vue@[^/]+\//g, '.pnpm/vue@0.0.0/') dirs.stale = await withoutVue('stale', { files: Object.fromEntries(['', '.app', '.node', '.server', '.shared'].map(part => [`.nuxt/tsconfig${part}.json`, staleVue])) }) + dirs.standalone = await withoutVue('standalone', { files: { 'tsconfig.json': JSON.stringify({ compilerOptions: { strict: true, target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'preserve', allowImportingTsExtensions: true, noEmit: true }, include: ['src'] }) } }) await Promise.all([ - ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths', 'stale'].map(name => step(name, tsdown(dirs[name]!))), + ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths', 'stale', 'standalone'].map(name => step(name, tsdown(dirs[name]!))), step('compose', tsdown(dirs.compose)), step('packageImports', tsdown(dirs.packageImports)), step('warnings', tsdown(dirs.warnings)) @@ -600,4 +601,13 @@ describe('a module that does not install `vue`', () => { await expectTyped(dirs.stale!) expect(await read(dirs.stale!, '.nuxt/tsconfig.app.json')).not.toContain('vue@0.0.0') }) + + it('should fail when `vue` does not resolve from the components whose declarations it types', () => { + const output = expectFailed('standalone') + expect(output).toContain('NUXT_MB_B0206: `vue` does not resolve from these components') + expect(output).toContain('`src/runtime/components/ErrorState.vue`') + expect(output).toContain('`src/runtime/components/TestMe.vue`') + expect(output).not.toContain('RowActions.vue') + expect(exists(dirs.standalone!, 'dist')).toBe(false) + }) }) From fa583d79c92dd17acc18ba54c92632b9b6018ce1 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 23:35:04 +0000 Subject: [PATCH 5/8] test: build the stale `.nuxt` fixture on the drive of the repository --- test/builder.spec.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/builder.spec.ts b/test/builder.spec.ts index dfd30198..e13df477 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -283,7 +283,7 @@ export default { }) dirs.rootPaths = await withoutVue('root-paths', { files: { 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json')), compilerOptions: { paths: MY_PATHS } }) } }) const staleVue = (source: string) => source.replace(/\.pnpm\/vue@[^/]+\//g, '.pnpm/vue@0.0.0/') - dirs.stale = await withoutVue('stale', { files: Object.fromEntries(['', '.app', '.node', '.server', '.shared'].map(part => [`.nuxt/tsconfig${part}.json`, staleVue])) }) + dirs.stale = await fixture('.temp-builder/stale', { config: PLUGIN, files: Object.fromEntries(['', '.app', '.node', '.server', '.shared'].map(part => [`.nuxt/tsconfig${part}.json`, staleVue])) }) dirs.standalone = await withoutVue('standalone', { files: { 'tsconfig.json': JSON.stringify({ compilerOptions: { strict: true, target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'preserve', allowImportingTsExtensions: true, noEmit: true }, include: ['src'] }) } }) await Promise.all([ @@ -533,6 +533,13 @@ describe('with a root tsconfig that only lists references', () => { expect(await read(dirs.singleTsconfig!, 'dist/module.d.mts')).toBe(await read(dirs.moduleProject!, 'dist/module.d.mts')) }) + it('should prepare `.nuxt` again when its tsconfigs map a package into a directory that no longer exists', async () => { + expect(expectBuilt('stale')).toMatch(/\[NUXT_MB_B0102\] `\.nuxt` is out of date: its tsconfigs map `vue` into packages that are not installed/) + const [target] = JSON.parse(await read(dirs.stale!, '.nuxt/tsconfig.app.json')).compilerOptions.paths.vue + expect(target).not.toContain('vue@0.0.0') + expect(exists(dirs.stale!, '.nuxt', target)).toBe(true) + }) + it('should prepare a missing `.nuxt` without the declarations of module code when the module augments none of Nuxt\'s types', () => { expect(expectBuilt('appProject')).toContain('[NUXT_MB_B0101]') expect(exists(dirs.appProject!, '.nuxt/tsconfig.app.json')).toBe(true) @@ -595,13 +602,6 @@ describe('a module that does not install `vue`', () => { expect(output).not.toMatch(/leaves out `vue`/) }) - it('should prepare `.nuxt` again when its tsconfigs map a package into a directory that no longer exists', async () => { - const output = expectBuilt('stale') - expect(output).toMatch(/\[NUXT_MB_B0102\] `\.nuxt` is out of date: its tsconfigs map `vue` into packages that are not installed/) - await expectTyped(dirs.stale!) - expect(await read(dirs.stale!, '.nuxt/tsconfig.app.json')).not.toContain('vue@0.0.0') - }) - it('should fail when `vue` does not resolve from the components whose declarations it types', () => { const output = expectFailed('standalone') expect(output).toContain('NUXT_MB_B0206: `vue` does not resolve from these components') From 7039df82df36010756c7d6801978945e3279af50 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 23:36:58 +0000 Subject: [PATCH 6/8] fix: ignore commented-out script tags when finding generic components --- src/build/build.ts | 3 ++- test/builder.spec.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/build/build.ts b/src/build/build.ts index 1c2b5461..a95f4ce3 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -155,6 +155,7 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput } const SCRIPT_TAG_RE = /"']|"[^"]*"|'[^']*')*>/gi +const HTML_COMMENT_RE = //g /** * Fails when the library that the generated code of a single-file component imports does not @@ -164,7 +165,7 @@ const SCRIPT_TAG_RE = /"']|"[^"]*"|'[^']*')*>/gi async function assertResolvableVueLibrary(plan: BuildPlan) { const { cwd, rootTsconfig, directories } = plan const components = directories.flatMap(directory => globSync(['**/*.vue'], { cwd: directory.srcDir, ignore: EXCLUDE, absolute: true, onlyFiles: true }).map(file => normalize(file))) - const inferred = components.filter(file => ![...readFileSync(file, 'utf8').matchAll(SCRIPT_TAG_RE)].some(([tag]) => /\ssetup\b/.test(tag) && /\sgeneric\s*=/.test(tag))) + const inferred = components.filter(file => ![...readFileSync(file, 'utf8').replace(HTML_COMMENT_RE, '').matchAll(SCRIPT_TAG_RE)].some(([tag]) => /\ssetup\b/.test(tag) && /\sgeneric\s*=/.test(tag))) if (!rootTsconfig || !inferred.length) { return } diff --git a/test/builder.spec.ts b/test/builder.spec.ts index e13df477..4010abb7 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -284,7 +284,7 @@ export default { dirs.rootPaths = await withoutVue('root-paths', { files: { 'tsconfig.json': JSON.stringify({ ...JSON.parse(REFERENCES('./.nuxt/tsconfig.node.json')), compilerOptions: { paths: MY_PATHS } }) } }) const staleVue = (source: string) => source.replace(/\.pnpm\/vue@[^/]+\//g, '.pnpm/vue@0.0.0/') dirs.stale = await fixture('.temp-builder/stale', { config: PLUGIN, files: Object.fromEntries(['', '.app', '.node', '.server', '.shared'].map(part => [`.nuxt/tsconfig${part}.json`, staleVue])) }) - dirs.standalone = await withoutVue('standalone', { files: { 'tsconfig.json': JSON.stringify({ compilerOptions: { strict: true, target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'preserve', allowImportingTsExtensions: true, noEmit: true }, include: ['src'] }) } }) + dirs.standalone = await withoutVue('standalone', { files: { 'src/runtime/components/Commented.vue': `\n\n\n\n`, 'tsconfig.json': JSON.stringify({ compilerOptions: { strict: true, target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'preserve', allowImportingTsExtensions: true, noEmit: true }, include: ['src'] }) } }) await Promise.all([ ...['legacyPaths', 'ownVue', 'partPaths', 'rootPaths', 'stale', 'standalone'].map(name => step(name, tsdown(dirs[name]!))), @@ -607,6 +607,7 @@ describe('a module that does not install `vue`', () => { expect(output).toContain('NUXT_MB_B0206: `vue` does not resolve from these components') expect(output).toContain('`src/runtime/components/ErrorState.vue`') expect(output).toContain('`src/runtime/components/TestMe.vue`') + expect(output).toContain('`src/runtime/components/Commented.vue`') expect(output).not.toContain('RowActions.vue') expect(exists(dirs.standalone!, 'dist')).toBe(false) }) From b00ad11daa3805731f02ba4047b047815d055da9 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 23:37:24 +0000 Subject: [PATCH 7/8] fix: check every target of a `.nuxt` alias for a missing package --- src/transpile/tsconfig.ts | 4 ++-- test/unit.spec.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 45f91667..b211ae11 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -429,8 +429,8 @@ export function missingPathPackages(dir: string): { aliases: string[], tsconfigs continue } for (const [alias, targets] of Object.entries(paths ?? {})) { - const packageDir = targets.map(target => resolve(buildDir, target).match(PACKAGE_DIR_RE)?.[1]).find(Boolean) - if (packageDir && !existsSync(packageDir)) { + const packageDirs = targets.flatMap(target => resolve(buildDir, target).match(PACKAGE_DIR_RE)?.[1] ?? []) + if (packageDirs.some(packageDir => !existsSync(packageDir))) { aliases.add(alias) tsconfigs.add(file) } diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 4d6a3fc2..8b729c1c 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -1438,12 +1438,13 @@ describe('missingPathPackages', () => { 'vue': ['../node_modules/.pnpm/vue@3.0.0/node_modules/vue'], '@unhead/vue': ['../node_modules/.pnpm/@unhead+vue@2.0.0/node_modules/@unhead/vue'], '#app-manifest': ['../node_modules/.cache/nuxt/manifest'], + 'vue-router': ['../node_modules/.pnpm/nuxt@4.0.0/node_modules/nuxt/dist/missing', '../node_modules/.pnpm/vue-router@4.0.0/node_modules/vue-router'], '#shared': ['../shared'], '#build/*': ['./*'], } await writeFile(join(cwd, '.nuxt/tsconfig.json'), JSON.stringify({ compilerOptions: { paths } })) await writeFile(join(cwd, '.nuxt/tsconfig.app.json'), JSON.stringify({ compilerOptions: { paths: { 'vue-demi': paths['vue-demi'] } } })) - expect(missingPathPackages(cwd)).toEqual({ aliases: ['vue', '@unhead/vue'], tsconfigs: [join(cwd, '.nuxt/tsconfig.json')] }) + expect(missingPathPackages(cwd)).toEqual({ aliases: ['vue', '@unhead/vue', 'vue-router'], tsconfigs: [join(cwd, '.nuxt/tsconfig.json')] }) }) }) From 3775027b1ada5ff145119de4817b35460760d33c Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 23:54:01 +0000 Subject: [PATCH 8/8] refactor: skip html comments while matching script tags --- src/build/build.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/build/build.ts b/src/build/build.ts index a95f4ce3..2e1e91ac 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -154,8 +154,7 @@ export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput plan.prepared = analyseSources(plan) } -const SCRIPT_TAG_RE = /"']|"[^"]*"|'[^']*')*>/gi -const HTML_COMMENT_RE = //g +const SCRIPT_TAG_OR_COMMENT_RE = /|$)|"']|"[^"]*"|'[^']*')*>/gi /** * Fails when the library that the generated code of a single-file component imports does not @@ -165,7 +164,7 @@ const HTML_COMMENT_RE = //g async function assertResolvableVueLibrary(plan: BuildPlan) { const { cwd, rootTsconfig, directories } = plan const components = directories.flatMap(directory => globSync(['**/*.vue'], { cwd: directory.srcDir, ignore: EXCLUDE, absolute: true, onlyFiles: true }).map(file => normalize(file))) - const inferred = components.filter(file => ![...readFileSync(file, 'utf8').replace(HTML_COMMENT_RE, '').matchAll(SCRIPT_TAG_RE)].some(([tag]) => /\ssetup\b/.test(tag) && /\sgeneric\s*=/.test(tag))) + const inferred = components.filter(file => ![...readFileSync(file, 'utf8').matchAll(SCRIPT_TAG_OR_COMMENT_RE)].some(([tag]) => /^