package.json pins Node and pnpm in devEngines, and pnpm downloads them when they are missing.
pnpm install
pnpm dev:prepare| Script | What it runs |
|---|---|
pnpm build |
tsdown, building this package into dist |
pnpm test |
the vitest suite (pnpm vitest run for one pass) |
pnpm test:types |
vue-tsc over the package and the example |
pnpm test:knip |
unused files, exports and dependencies |
pnpm test:pack |
packs the example and checks it with attw and publint |
pnpm lint |
ESLint |
pnpm nuxt-module-build |
the CLI from source, for example pnpm nuxt-module-build build ./example |
Pages in docs/ are published on nuxt.com, so links between them use nuxt.com paths. Build messages link to headings of docs/upgrade-v2.md on GitHub (see Diagnostics), so that page is plain GitHub-flavoured Markdown, and links to the other pages by relative path, such as ./5.typescript.md#module-code. A unit test checks that every linked heading exists.
The package has three entry points:
src/cli.tsis thenuxt-module-buildbinary, also run asnuxt build-module. It has two subcommands,buildandprepare.src/tsdown/index.tsexportsbuilder(), the tsdown plugin that builds a module. This is how modules build:tsdownwithplugins: [builder()].src/index.tsexportsbuild,prepareand the unbuild-compatibledefineBuildConfig.
| Directory | Contents |
|---|---|
src/commands/ |
The CLI subcommands, plus config-file.ts, which finds the module's tsdown config and reads the builder() options from it. |
src/tsdown/ |
The builder() plugin. plugin.ts creates it, and setup.ts turns the tsdown config into a build. It adds the plugins, hooks into tsdown's lifecycle, and handles watch mode. externals.ts, unchanged.ts and report.ts are the plugins and helpers that setup.ts uses, and dts.ts generates the declarations of the bundled entries. build.ts runs tsdown for nuxt-module-build build. |
src/build/ |
The build itself, independent of tsdown's plugin API:options.ts resolves builder() options.build.ts resolves a BuildPlan and runs the steps before and after the bundle.loader.ts imports module code and checks that Node can load it.package.ts holds the package.json checks.types.ts and module-declarations.ts write types.d.mts and the declarations prepare generates.aliases.ts rewrites #app in declarations.directives.ts wraps the oxc transform of runtime files so that TypeScript directive comments are left out.unchecked.ts finds the TypeScript files that no tsconfig the module references includes, for prepare's note.engine.ts loads the declaration engine that declarations.engine selects, with its diagnostics. |
src/transpile/ |
transpileDir(), the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and .vue files with vue.ts, compiles stylesheets with stylesheets.ts, emits declarations with declarations.ts (reused from node_modules/.cache while their inputs are unchanged, see cache.ts) through a declaration engine (engine.ts for the module's own TypeScript, native.ts for TypeScript 7 and tsrs), rewrites import specifiers with specifiers.ts, resolves the tsconfig of each file with tsconfig.ts. oxc.ts loads the oxc bindings of the rolldown that tsdown depends on, whose parser the whole package parses scripts with, and typescript.ts loads the JavaScript API of TypeScript that the whole package uses (the module's own typescript when it has one, or else @typescript/typescript6). The directory imports nothing outside it but src/utils.ts, so it can be extracted later. |
src/legacy/ |
Compatibility with v1 and unbuild (see Legacy code). |
src/diagnostics.ts |
The codes of every error and warning the builder reports (see Diagnostics). |
src/utils.ts |
Path, file and regex helpers shared across directories, and logger, which prints diagnostics outside a tsdown build. |
builder() acts in tsdown's tsdownConfig hook. setupBuilder then:
- Refuses tsdown options that
builder()sets itself, resolves the module root (following symlinks) and the output directory, and checks the publishedpackage.jsonpaths. - Resolves the
builder()options into aModuleConfig(src/build/options.ts). When.nuxtis missing, it runspreparefirst. - Resolves a
BuildPlan(resolveBuildinsrc/build/build.ts), with these parts:- the bundled entries (
src/moduleandentries); - the transpiled directories (
src/runtimeand directory entries); - the tsconfigs for declarations;
- the module's self-reference paths;
- a cache key for
.vuedeclarations.
- the bundled entries (
- Sets
entry,format,dts,cleananddeps.neverBundle, anddeps.onlyBundleunless the config sets it. AddsruntimeExternals(bundled code imports runtime files fromdistinstead of inlining them), the declaration externals,bundledPackages(which fails on packages thatdeps.onlyBundleleaves out), replacements, and onetranspileDir()per directory.
Then, once per build:
build:preparerunsprepareBuild:- the
build:beforehook; - the check that module code loads with Node;
- emptying the output directory;
- the derived tsconfig that declaration generation reads.
- the
- During the bundle, the bundled entries and each
transpileDir()emit their files. - After writing,
finishBuilddoes the rest. Any failure removes the output directory, except in watch mode.- Imports the built
module.mjsto writemodule.json. - Writes
types.d.mts. - Rewrites
#appin declarations. - Checks the package
importsthat the output uses. - Runs the
build:donehook.
- Imports the built
In watch mode the output directory is kept, unchanged files aren't rewritten (unchanged.ts), and files a rebuild no longer emits are removed. Each transpileDir() passes one declaration session to its .vue declaration programs, so the programs of one build share the sources they parse, a rebuild doesn't parse unchanged sources again, and the session is dropped when the watcher closes.
src/tsdown/build.ts runs tsdown programmatically. With a tsdown config in the module root, it builds with that config and fails unless it uses builder(). Without one, it builds with createBuilder() and loadLegacyModuleConfig. That reads build.config.* or the build field of package.json, so a v1 module builds without a tsdown config.
src/commands/prepare.ts does the following:
- Loads the same options as a build.
- Checks that module code loads with Node, then imports
src/module.tswithimportModule. - Runs
nuxt prepareon the module root with that module installed.
That writes .nuxt, including:
- the tsconfigs of each context, with
erasableSyntaxOnlyin the node tsconfig when the root tsconfig hasreferencesand itscompilerOptionsleave the option unset; - with a root tsconfig that has
references,.nuxt/nuxt.module.d.ts, which the node tsconfig includes in place of.nuxt/nuxt.d.ts: a copy of it without Nitro'stypes/nitro-imports.d.ts, so the module code project doesn't load the server sources that the server's auto-imports point at; .nuxt/module-builder/types.d.mts, which source exports point at;- the declarations that resolve the module's own package name inside its type checks.
With a root tsconfig that has references, it then lists the module's TypeScript files that none of the referenced projects include, once per process and outside CI.
Nuxt 5, and a playground that loads the module from its sources, import src/module.ts with Node as written. Node strips types and resolves imports exactly as they are written. findModuleCodeIssues in src/build/loader.ts reports each import and each piece of syntax that breaks this, with its file, line, column and fix. build, tsdown and prepare all stop on these findings. It follows relative imports without their extension to their files, so one run reports every file it reaches, and it lists the imports that resolve to no file as unfollowed, which only accompany other findings. Keep this check strict: code that passes it has to run under Node.
src/legacy/ holds what only v1 and unbuild users need:
build-config.tsreads and translatesbuild.config.*and thebuild/unbuildfields ofpackage.json, and emulates the unbuild hooks.define.tscontainsdefineBuildConfigand its types.package-paths.tsexplains v1package.jsonpaths such asmodule.cjs.
Core code doesn't import legacy types. The call sites are:
src/index.tssrc/tsdown/build.tssrc/commands/prepare.tssrc/build/options.tssrc/build/package.ts
Their tests live in test/legacy.spec.ts. To drop unbuild compatibility, delete the directory and that spec, then fix the call sites.
Errors and warnings that a module author can act on are nostics diagnostics, defined in src/diagnostics.ts. Each has a code: NUXT_MB_, then B (build), C (config) or D (v1 and unbuild compatibility), then four digits. Codes are grouped by hundreds within each area, and a published code is never renamed or reused.
There are two catalogs:
errorsfor diagnostics that are thrown, as inthrow errors.NUXT_MB_C0012({ label, path }). Creating one prints nothing.tsdownand rolldown print the stack of an error, so a diagnostic's stack is its first line followed by thefixand docs lines, without frames. rolldown wraps an error thrown from a plugin hook in a build error with its own frames, sosetupBuilderunwraps a build error made of one diagnostic before tsdown prints it, with the stack of itscauseafter it.nuxt-module-buildprints a thrown diagnostic withformatDiagnosticinstead, followed by itscause.warningsfor diagnostics that are printed when created, as warnings, or as info or errors when the call passes{ method }.
During a build, diagnostics are printed with tsdown's logger (useBuildLogger()), so the build's logLevel, failOnWarn and suppressWarnings apply to them. setupBuilder hands it tsdown's global logger, then the logger of the resolved config. Outside a build, as in nuxt-module-build prepare, they are printed with logger from src/utils.ts. tsdown is a peer dependency, so src/diagnostics.ts only imports its types.
To add one, add an entry to errorCodes or warningCodes with the next free number in its group:
whysays what is wrong and becomes the message.fixsays what to do. Neither repeats the other.docsis the#anchorof the heading ofdocs/upgrade-v2.mdthat explains it, orfalse. The printed link points at the guide at the release tag of the version that prints it,GUIDE_URL.- The call passes
sources: the absolute path of every file that thewhyorfixnames, with:line:columnwhen it names a position. In a terminal, each file that exists is linked where thewhyorfixnames it, by the end of its path. URLs in the text and the docs link are linked as well. - The tsconfig sets
isolatedDeclarations, sowhyandfixare string literals or functions with a: stringreturn type, anddocsis a string literal.
Tests assert the code, such as diagnostic('NUXT_MB_C0012') or reported('NUXT_MB_C0201') from test/utils.ts, and the values that matter, rather than the message.
Errors that only the builder handles, such as DeclarationError, and those of src/transpile/, which imports nothing outside its directory, are plain errors.
| Spec | Surface |
|---|---|
test/cli.spec.ts |
nuxt-module-build build and prepare |
test/builder.spec.ts |
tsdown with builder(), and tsconfig references |
test/watch.spec.ts |
tsdown --watch |
test/transpile-dir.spec.ts |
transpileDir() on its own |
test/engines.spec.ts |
declarations.engine and declarations.isolated; the native engines' tests skip, with the reason, where they cannot run |
test/legacy.spec.ts |
build.config.*, the build field, defineBuildConfig |
test/unit.spec.ts |
pure helpers |
This repository installs the native declaration engines, which a build picks up by default, so vitest.config.mts sets NUXT_MODULE_BUILDER_DECLARATION_ENGINE=typescript for every spec but test/engines.spec.ts.
Each e2e spec builds its fixtures in one beforeAll, in parallel, and its it blocks only read the results:
fixture()intest/utils.tscopiesexample/(or another fixture) into a gitignored.temp-*directory, with files,package.jsonfields and tsconfigpathschanged.cli(),tsdown()andrun()start processes, and the number running at once is capped at one per CPU.
Add a case to an existing fixture when it doesn't conflict with that fixture's other cases, and create a new fixture only when it does. Name tests it('should ...').
Coverage of the CLI processes:
NODE_V8_COVERAGE=/tmp/cov pnpm vitest run
pnpm dlx c8@10 report --temp-directory /tmp/cov --include 'src/**' --reporter text --all --src .