Skip to content
Merged
6 changes: 5 additions & 1 deletion docs/5.typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,15 @@ 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).

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.

Expand Down
9 changes: 8 additions & 1 deletion docs/upgrade-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand All @@ -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).
Expand Down Expand Up @@ -439,6 +440,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.
Expand Down
47 changes: 45 additions & 2 deletions src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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'
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand All @@ -124,13 +146,34 @@ 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 })
}
plan.prepared = analyseSources(plan)
}

const SCRIPT_TAG_OR_COMMENT_RE = /<!--[\s\S]*?(?:-->|$)|<script\b(?:[^>"']|"[^"]*"|'[^']*')*>/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_OR_COMMENT_RE)].some(([tag]) => /^<script\b/i.test(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.
Expand Down
23 changes: 23 additions & 0 deletions src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -78,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:',
Expand Down Expand Up @@ -222,6 +232,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<ModuleOptions> = defineNuxtModule<ModuleOptions>({ /* ... */ })\n export default module\n\nrather than `export default defineNuxtModule<ModuleOptions>({ /* ... */ })`.',
Expand Down Expand Up @@ -266,6 +281,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.`,
Expand Down
Loading
Loading