From 097d04020e522a98b4702aea7f19f5bfbaef5113 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Thu, 12 Nov 2026 19:29:39 +0000 Subject: [PATCH 01/28] docs: add module-builder docs for nuxt.com --- README.md | 207 ++++-------------------------------- docs/.navigation.yml | 3 + docs/1.project-structure.md | 167 +++++++++++++++++++++++++++++ docs/2.commands.md | 116 ++++++++++++++++++++ docs/3.configuration.md | 94 ++++++++++++++++ docs/4.typescript.md | 121 +++++++++++++++++++++ docs/5.output.md | 111 +++++++++++++++++++ docs/6.exports.md | 112 +++++++++++++++++++ docs/7.transpile-dir.md | 82 ++++++++++++++ docs/index.md | 86 +++++++++++++++ docs/upgrade-v2.md | 21 ++-- src/build/guide.ts | 62 ++++++----- test/unit.spec.ts | 11 +- 13 files changed, 967 insertions(+), 226 deletions(-) create mode 100644 docs/.navigation.yml create mode 100644 docs/1.project-structure.md create mode 100644 docs/2.commands.md create mode 100644 docs/3.configuration.md create mode 100644 docs/4.typescript.md create mode 100644 docs/5.output.md create mode 100644 docs/6.exports.md create mode 100644 docs/7.transpile-dir.md create mode 100644 docs/index.md diff --git a/README.md b/README.md index 50182d34..3195fc3c 100644 --- a/README.md +++ b/README.md @@ -9,204 +9,35 @@ ## Features -- Compatible with Nuxt 3 and Nuxt Kit -- Unified build with [tsdown](https://tsdown.dev) -- Automated build config using last module spec -- Typescript and ESM support -- Auto generated types and shims for `@nuxt/schema` - -We recommend to checkout the [Nuxt modules author guide](https://nuxt.com/docs/guide/going-further/modules) before starting with the module-builder. - -If you're upgrading a module from v1, follow the [upgrade guide](./docs/upgrade-v2.md). - -## Requirements - -For a user to use a module generated from module-builder, it's recommended they have: -- Node.js >= 18.x. _Latest Node LTS preferred_ -- Nuxt 3+. +- Builds modules for Nuxt 3 and later, with no configuration for the [module starter](https://github.com/nuxt/starter/tree/module) layout +- Bundles the module entry with [tsdown](https://tsdown.dev), and transpiles the runtime directory file by file +- Generates declarations against the module's own `.nuxt`, for `.ts` and `.vue` files alike +- Writes the type shims that give `nuxt.config` autocompletion for the module's options and hooks +- Stubs `dist` for development, so a playground runs the module's sources directly ## Quick start -Get started with our [module starter](https://github.com/nuxt/starter/tree/module): +Create a module from the [module starter](https://github.com/nuxt/starter/tree/module): ```bash npm create nuxt -- -t module my-module ``` -## Project structure - -The module builder requires a special project structure. You can check out the [module template](https://github.com/nuxt/starter/tree/module). - -### `src/module.ts` - -The entrypoint for module definition. - -A default export using `defineNuxtModule` and `ModuleOptions` type export is expected. - -You could also optionally export `ModuleHooks` or `ModuleRuntimeHooks` to annotate any custom hooks the module uses. - -```ts [src/module.ts] -import { defineNuxtModule } from '@nuxt/kit' - -export interface ModuleOptions { - apiKey: string -} - -export interface ModuleHooks { - 'my-module:init': any -} - -export interface ModuleRuntimeHooks { - 'my-module:runtime-hook': any -} - -export interface ModuleRuntimeConfig { - PRIVATE_NAME: string -} - -export interface ModulePublicRuntimeConfig { - NAME: string -} - -export default defineNuxtModule({ - meta: { - name: 'my-module', - configKey: 'myModule' - }, - defaults: { - apiKey: 'test' - }, - async setup (moduleOptions, nuxt) { - // Write module logic in setup function - } -}) -``` - -### `src/runtime/` - -Any runtime file and code that we need to provide by module including plugins, composables and server api, should be in this directory. - -Each file is transpiled individually to `dist/runtime/`. - - - -### `package.json`: - -A minimum `package.json` should look like this. It points at the module's sources while you develop, and pnpm publishes the `dist` paths in `publishConfig` in their place: - -```json [package.json] -{ - "name": "my-module", - "license": "MIT", - "version": "1.0.0", - "exports": { - ".": { - "types": "./.nuxt/module-builder/types.d.mts", - "import": "./src/module.ts" - } - }, - "main": "./src/module.ts", - "types": "./.nuxt/module-builder/types.d.mts", - "files": [ - "dist" - ], - "publishConfig": { - "exports": { - ".": { - "types": "./dist/types.d.mts", - "import": "./dist/module.mjs" - } - }, - "main": "./dist/module.mjs", - "types": "./dist/types.d.mts" - }, - "scripts": { - "dev": "nuxt dev playground", - "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground", - "prepack": "tsdown" - }, - "dependencies": { - "@nuxt/kit": "latest" - }, - "devDependencies": { - "@nuxt/module-builder": "latest", - "tsdown": "^0.23.7" - } -} -``` - -`tsdown` is a peer dependency, so install it alongside `@nuxt/module-builder`. `tsdown` builds the module with the `tsdown.config.ts` shown in [Build configuration](#build-configuration); without one, use `"prepack": "nuxt-module-build build"` instead. `nuxt-module-build prepare` writes `.nuxt/module-builder/types.d.mts`, the declarations of `src/module.ts` with the module's type augmentations. pnpm and Yarn 4 publish `publishConfig` in place of these fields; npm, Yarn 3 and earlier, and bun don't, and packing with them fails. With those, point `package.json` at `dist` and run `tsdown --watch` while you develop. See [Developing a module](./docs/upgrade-v2.md#developing-a-module). - -Module code (`src/module.ts`, the files it imports by value, and the build config) has to load with Node as it is: relative imports carry their `.ts` extension, and TypeScript syntax that stripping types doesn't remove, tsconfig `paths` aliases, value imports of `.vue` and `.tsx` files, JSON without `with { type: 'json' }`, and value imports of `#app`, `#imports`, and `#build/*` aren't allowed. See [Module code loads with Node](./docs/upgrade-v2.md#module-code-loads-with-node). +Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `typescript` installed alongside `@nuxt/module-builder`. Apps that install a built module need Nuxt 3 or later. -### Build configuration +## Documentation -Module builder builds with [tsdown](https://tsdown.dev), through the `builder()` plugin. Add it to a `tsdown.config.ts`, and build with `tsdown`: +- [Getting started](./docs/index.md) +- [Project structure](./docs/1.project-structure.md) +- [Commands](./docs/2.commands.md): `build`, `build --stub`, and `prepare` +- [Configuration](./docs/3.configuration.md): extra entries, and the deprecated `build.config.ts` +- [TypeScript](./docs/4.typescript.md): the module's `tsconfig.json`, and its declarations +- [Build output](./docs/5.output.md) +- [Exports](./docs/6.exports.md): subpath exports, including runtime components +- [Transpiling a directory](./docs/7.transpile-dir.md): the `transpileDir` rolldown plugin +- [Upgrading to v2](./docs/upgrade-v2.md) -```ts [tsdown.config.ts] -import { builder } from '@nuxt/module-builder/tsdown' -import { defineConfig } from 'tsdown' - -export default defineConfig({ - plugins: [ - builder({ - // entrypoints other than `src/module` - entries: ['./src/utils'], - }), - ], -}) -``` - -`nuxt-module-build build` builds the same `dist`, with this config or, without one, with no options. `builder()` also takes `externals` and `replace`, and other tsdown options apply as usual apart from the ones the plugin sets. See [tsdown config](./docs/upgrade-v2.md#tsdown-config) in the upgrade guide. - -> [!WARNING] -> `build.config.ts` and the `unbuild` field of `package.json` are deprecated. Without a `tsdown.config.ts`, -> the build still applies their `entries`, `externals`, `replace`, `rollup.replace`, and `sourcemap` options, -> and the `build:before`, `rollup:done`, and `build:done` hooks, and reads `build.entries` from `package.json`. -> See [Moving from build.config.ts](./docs/upgrade-v2.md#moving-from-buildconfigts) in the upgrade guide. - -## Dist files - -Module builder generates dist files in `dist/` directory: - -- `module.mjs`: Module entrypoint build from `src/module` -- `module.json`: Module meta extracted from `module.mjs` + `package.json` -- `types.d.mts`: Exported types in addition to shims for `nuxt.config` auto completion. -- `runtime/*`: Individually transpiled files - - JavaScript and `.ts` files are transpiled to `.js`, with their types extracted to a `.d.ts` file of the same name - - `.vue` files are transpiled to `.vue`, with their types extracted to `.vue.d.ts` and `.d.vue.ts` files - - `.css` files have their nesting flattened, and are vendor-prefixed and minified - - `.scss` and `.sass` files are compiled to `.css` with the module's `sass` or `sass-embedded`; `_` partials aren't emitted - - Other files are copied as they are - -## Output size - -Each build reports its output size: a summary plus one line per bundled entry and runtime directory for a module with runtime directories, or one line per file otherwise. Set `report` in `tsdown.config.ts` to change it (`{ summary: true }`, `{ gzip: false }`, `{ brotli: true }`, or `false`). For size checks in CI, `npm pack --dry-run --json` lists exactly what gets published: each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`: - -```bash -npm pack --dry-run --json | jq '.[0] | { size, unpackedSize }' -``` - -## Transpiling a directory with tsdown - -The runtime build is a rolldown plugin, `transpileDir`, exported from `@nuxt/module-builder/rolldown`. Use it in any tsdown or rolldown build that transpiles a directory file by file instead of bundling it: - -```ts -// tsdown.config.ts -import { defineConfig } from 'tsdown' -import { transpileDir } from '@nuxt/module-builder/rolldown' - -export default defineConfig({ - entry: ['src/index.ts'], - plugins: [ - transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }), - ], -}) -``` - -Every file under `srcDir` is emitted under `outBase` in the build's output directory, with its name intact apart from the extension. Scripts become `.js` (or `.mjs`), and compiled Sass becomes `.css`. Test and story files are excluded by default. Scripts are transpiled with oxc and keep their imports as written, apart from relative imports, which get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Dist files](#dist-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. - -The options are documented on the `TranspileDirOptions` type. The `resolveExternal` option controls what happens to relative imports that resolve outside `srcDir`. A build with nothing to bundle can pass `emptyEntry`, from the same export, as its `entry`. +For writing the module itself, read the [Nuxt Module Author Guide](https://nuxt.com/docs/guide/modules). ## ๐Ÿ’ป Development @@ -215,6 +46,8 @@ The options are documented on the `TranspileDirOptions` type. The `resolveExtern - Install dependencies using `pnpm install` - Try building [example module](./example) using `pnpm example:build` +Pages in [`docs/`](./docs) are written for [nuxt.com](https://nuxt.com), so links between them use nuxt.com paths. + ## License [MIT](./LICENSE) - Made with ๐Ÿ’š diff --git a/docs/.navigation.yml b/docs/.navigation.yml new file mode 100644 index 00000000..a5afc0e2 --- /dev/null +++ b/docs/.navigation.yml @@ -0,0 +1,3 @@ +title: Module Builder +titleTemplate: '%s ยท Nuxt Module Builder' +icon: i-lucide-package diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md new file mode 100644 index 00000000..35b363df --- /dev/null +++ b/docs/1.project-structure.md @@ -0,0 +1,167 @@ +--- +title: Project Structure +description: The files and directories that `@nuxt/module-builder` reads. +--- + +The builder expects the layout of the [module starter](https://github.com/nuxt/starter/tree/module): + +```bash +my-module/ +โ”œโ”€โ”€ src/ +โ”‚ โ”œโ”€โ”€ module.ts # the module definition +โ”‚ โ””โ”€โ”€ runtime/ # code added to the app that installs the module +โ”œโ”€โ”€ playground/ # a Nuxt app that installs the module +โ”œโ”€โ”€ package.json +โ””โ”€โ”€ tsconfig.json +``` + +## `src/module.ts` + +The module entry. Its default export is the module definition, created with `defineNuxtModule` from `@nuxt/kit`. The build bundles it into `dist/module.mjs`. + +The builder also reads these type exports, and adds them to the types of the app that installs the module: + +| Export | Augments | Used for | +|---|---|---| +| `ModuleOptions` | | The module's key in `nuxt.config`. When it isn't exported, it's inferred from the default export. | +| `ModuleHooks` | `NuxtHooks` from `@nuxt/schema` | Build-time hooks the module calls, which apps and other modules register with `hooks` or `nuxt.hook()`. | +| `ModuleRuntimeHooks` | `RuntimeNuxtHooks` from `#app` | Runtime hooks the module calls, which plugins register with `nuxtApp.hook()`. | +| `ModuleRuntimeConfig` | `RuntimeConfig` from `@nuxt/schema` | Private runtime config keys the module adds. | +| `ModulePublicRuntimeConfig` | `PublicRuntimeConfig` from `@nuxt/schema` | Public runtime config keys the module adds. | + +```ts [src/module.ts] +import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' + +export interface ModuleOptions { + apiKey: string +} + +export interface ModuleHooks { + 'my-module:init': (options: ModuleOptions) => void +} + +export interface ModuleRuntimeHooks { + 'my-module:ready': () => void +} + +export interface ModulePublicRuntimeConfig { + myModule: { apiKey: string } +} + +export default defineNuxtModule({ + meta: { + name: 'my-module', + configKey: 'myModule', + }, + defaults: { + apiKey: '', + }, + setup(options, nuxt) { + const resolver = createResolver(import.meta.url) + + nuxt.options.runtimeConfig.public.myModule = { apiKey: options.apiKey } + addPlugin(resolver.resolve('./runtime/plugin')) + }, +}) +``` + +Relative imports in `src/module.ts`, and in every file it imports outside the runtime directories, carry the imported file's extension: `./utils.ts`, not `./utils`. The [stub build](/docs/guide/modules/module-builder/commands#build-stub) and [`prepare`](/docs/guide/modules/module-builder/commands#prepare) load these files with Node, which resolves relative specifiers as written. Type-only imports are exempt. + +Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/plugin.ts` is emitted as `dist/runtime/plugin.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source in development, and the `.js` output once the module is published. + +## `src/runtime/` + +Code that the module adds to the app: components, composables, plugins, server routes, stylesheets, and any other files. The module registers them from `setup()`, with utilities such as `addPlugin`, `addComponent`, or `addServerHandler`. + +Each file is transpiled on its own into `dist/runtime/`, keeping its name and its imports. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. + +Files in the runtime directory can't rely on auto-imports, since Nuxt doesn't apply them to files in `node_modules`. Import what you use from `#imports`, or from the package that provides it: + +```ts [src/runtime/composables/useGreeting.ts] +import { useRuntimeConfig } from '#imports' + +export function useGreeting() { + return `Hello from ${useRuntimeConfig().public.myModule.apiKey}` +} +``` + +The `.nuxt` that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) generates for your module disables auto-imports too. A missing import is then a type error, in your editor and in the build. + +To transpile another directory in the same way, add it to [`build.entries`](/docs/guide/modules/module-builder/configuration#directory-entries). + +## `playground/` + +A Nuxt app that installs your module, to try it out while you develop it. The starter installs the module by its package name: + +```json [playground/package.json] +{ + "dependencies": { + "my-module": "file:.." + } +} +``` + +```ts [playground/nuxt.config.ts] +export default defineNuxtConfig({ + modules: ['my-module'], + myModule: {}, +}) +``` + +The playground therefore loads the module through its `package.json` `exports`, from `dist`. A [stub build](/docs/guide/modules/module-builder/commands#build-stub) points `dist` at your sources, so the playground runs them without a full build after every change. + +## `package.json` + +A minimal `package.json` for a module: + +```json [package.json] +{ + "name": "my-module", + "version": "1.0.0", + "license": "MIT", + "type": "module", + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + } + }, + "main": "./dist/module.mjs", + "typesVersions": { + "*": { + ".": [ + "./dist/types.d.mts" + ] + } + }, + "files": [ + "dist" + ], + "scripts": { + "prepack": "nuxt-module-build build", + "dev": "nuxt dev playground", + "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground" + }, + "dependencies": { + "@nuxt/kit": "^4.0.0" + }, + "devDependencies": { + "@nuxt/module-builder": "^2.0.0", + "nuxt": "^4.0.0", + "tsdown": "^0.23.7", + "typescript": "^5.9.3 || ^6.0.0" + } +} +``` + +- `exports["."].types` points at `dist/types.d.mts`, which re-exports the module's types along with the [augmentations](#srcmodulets) above. +- `typesVersions` resolves the same file for consumers that use TypeScript's `node10` module resolution, which ignores `exports`. +- `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. Any other package that the module entry imports, such as a `devDependency`, is bundled into it. + +After every build, the builder checks the paths in `exports`, `main`, `module`, `types`, and `typesVersions`, and warns about any that the build didn't produce. + +To publish more entry points, such as `my-module/utils` or `my-module/components`, see [Exports](/docs/guide/modules/module-builder/exports). + +## `tsconfig.json` + +The module's own `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates in the module root. See [TypeScript](/docs/guide/modules/module-builder/typescript). diff --git a/docs/2.commands.md b/docs/2.commands.md new file mode 100644 index 00000000..c87ce7f0 --- /dev/null +++ b/docs/2.commands.md @@ -0,0 +1,116 @@ +--- +title: Commands +description: The `nuxt-module-build` commands, and how they fit together while you develop and publish a module. +links: + - label: Source + icon: i-simple-icons-github + to: https://github.com/nuxt/module-builder/tree/main/src/commands + size: xs +--- + +`@nuxt/module-builder` installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. + +[`nuxt build-module`](/docs/api/commands/build-module) from the Nuxt CLI runs the same builder. + +## `build` + +```bash [Terminal] +npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] [--stub] +``` + +Builds the module for publishing. This is the command that the `prepack` script runs: + +1. If `.nuxt/tsconfig.json` is missing from the module root, it runs [`prepare`](#prepare) first. +2. It reads the [build configuration](/docs/guide/modules/module-builder/configuration) and checks that every relative import in the module code carries its extension. +3. It empties the output directory. +4. It bundles `src/module.ts`, and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries), with tsdown. +5. It transpiles `src/runtime/`, and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries), file by file. +6. It generates the declarations of every entry and runtime file, using the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). +7. It loads the built module to write `dist/module.json`, and writes `dist/types.d.mts`. +8. It checks the paths in `package.json` against the files it produced. + +The build fails when a declaration can't be generated correctly. Other type errors are reported as warnings. See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) for both. + +See [Build output](/docs/guide/modules/module-builder/output) for the files the build writes. + +### Arguments + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| Option | Default | Description | +|---|---|---| +| `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | +| `--outDir=` | `dist` | The output directory, relative to the module root. It's emptied before every build, so it must be inside the module. | +| `--sourcemap` | `false` | Emit a source map next to every script. | +| `--stub` | `false` | Write a [stub build](#build-stub) instead. | + +## `build --stub` + +```bash [Terminal] +npx nuxt-module-build build --stub [ROOTDIR] [--cwd=] [--outDir=] +``` + +Writes `dist` as a set of re-exports of your sources, so that anything which loads the module by its package name runs `src/` directly. Use it while you develop the module, with a playground, an app in the same monorepo, or tests that install the module by name. Changes to `src/` don't need another build. + +A stub build writes: + +- `dist/module.mjs`, which re-exports `src/module.ts`. +- `dist/module.d.mts`, which re-exports the types of `src/module.ts`. +- The same pair of files for every other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries). +- `dist/module.json` and `dist/types.d.mts`, as the full build does. + +It doesn't transpile the runtime directory or generate declarations. `src/module.ts` resolves runtime paths relative to itself, so `src/runtime/` is used as it is. A [subpath export](/docs/guide/modules/module-builder/exports) that points into `dist/runtime` resolves after a full build. + +Whatever imports the stub loads the TypeScript sources with its own loader, such as the playground's Nuxt. The builder itself loads `src/module.ts` to write `module.json`, with Node's type stripping. Syntax that Node can't strip (`enum`, `namespace`, parameter properties, JSX, and decorators, among others) is transpiled with oxc, which comes with `tsdown`. Without `tsdown`, the stub build fails and lists each use of such syntax. See [Stub builds](/docs/guide/modules/module-builder/upgrade-v2#stub-builds) in the upgrade guide. + +Options that a full build rejects in a [deprecated build config](/docs/guide/modules/module-builder/configuration#buildconfigts) are listed as a warning instead, and the stub build continues. + +## `prepare` + +```bash [Terminal] +npx nuxt-module-build prepare [ROOTDIR] [--cwd=] +``` + +Generates `.nuxt` in the module root. It runs `nuxt prepare` on the module root, as a Nuxt app with your module as its only module and auto-imports disabled. It writes nothing to `dist`. + +Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` it generates. That gives your editor, your type check, and the declarations that `build` generates the same types: `@nuxt/schema`, the `#app`, `#imports`, and `#build` aliases, and anything your module adds, such as its templates and server routes. See [TypeScript](/docs/guide/modules/module-builder/typescript). + +`prepare` loads `src/module.ts` in the same way as the stub build, so relative imports in module code need their extensions here too. Until they're in place, `prepare` lists the imports to fix and doesn't generate `.nuxt`. + +Run `prepare` again after a change to anything the module registers for types: its options, templates, type declarations, or server routes. + +### Arguments + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| Option | Default | Description | +|---|---|---| +| `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | + +## Developing a module + +The starter's `dev:prepare` script runs all three steps that a fresh checkout needs: + +```json [package.json] +{ + "scripts": { + "dev": "npm run dev:prepare && nuxt dev playground", + "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground", + "prepack": "nuxt-module-build build" + } +} +``` + +1. `nuxt-module-build build --stub` points `dist` at your sources. +2. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. +3. `nuxt prepare playground` generates the playground's `.nuxt`. The playground installs the module by its package name, so this step loads the stub from step 1. + +Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date. `build` runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. diff --git a/docs/3.configuration.md b/docs/3.configuration.md new file mode 100644 index 00000000..e663288e --- /dev/null +++ b/docs/3.configuration.md @@ -0,0 +1,94 @@ +--- +title: Configuration +description: Build entries other than `src/module.ts`, keep packages external, and the deprecated `build.config.ts`. +--- + +A module with `src/module.ts` and `src/runtime/` needs no configuration. To build other files, list them in the `build.entries` field of `package.json`: + +```json [package.json] +{ + "build": { + "entries": [ + "./src/utils", + { "input": "./src/kit/index", "name": "kit" }, + { "input": "src/features/", "outDir": "dist/features", "ext": "js" } + ] + } +} +``` + +An entry is either bundled, like `src/module.ts`, or a directory transpiled file by file, like `src/runtime/`. + +## Bundled entries + +A string, or an object with `input` and an optional `name`, is bundled with tsdown into a single file: + +| Option | Description | +|---|---| +| `input` | The entry file, relative to the module root. The extension can be left out. | +| `name` | The output name. Defaults to `input` without `src/` and without its extension. | + +Each bundled entry is written to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries). + +Bundled entries share the module entry's externals. These are never bundled: + +- `@nuxt/kit`, `@nuxt/schema`, `nuxt`, `vue`, and the `#app`, `#build`, and `#imports` aliases. +- Your module's own package name, and the `#` subpath imports in the `imports` field of `package.json`. +- `dependencies`, `peerDependencies`, and `optionalDependencies`. +- The packages in `build.externals`. + +Any other package an entry imports, such as a `devDependency`, is bundled into it. + +## Externals + +To keep a package that isn't a dependency out of the bundled entries, list it in the `build.externals` field of `package.json`. Each name also covers its subpaths, so `shiki` keeps `shiki/core` external too: + +```json [package.json] +{ + "build": { + "externals": ["shiki"] + } +} +``` + +The import is then kept as written, and resolves in the app that installs the module. + +## Directory entries + +An object whose `input` ends in `/` is a directory. Every file in it is transpiled on its own, in the same way as `src/runtime/`: + +| Option | Description | +|---|---| +| `input` | The source directory, relative to the module root, ending in `/`. | +| `outDir` | The output directory. Defaults to `dist`. It must be inside `dist`. | +| `ext` | The extension of emitted scripts: `mjs` (the default) or `js`. Declarations use the matching `.d.mts` or `.d.ts`. | + +The entry above writes the files of `src/features/` to `dist/features/`, with `.js` scripts and `.d.ts` declarations. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. + +Files in a directory entry follow the rules of the runtime directory. Their relative imports can leave out the extension, and module code that imports them points at their output instead of bundling them. + +## `build.config.ts` + +`build.config.ts` (or `.mts`, `.js`, `.mjs`) and the `unbuild` field of `package.json` are deprecated. The build reads them, warns, and still applies these options: + +- `entries`, in the shapes described above. +- `externals`: package names, as in [`build.externals`](#externals), and regular expressions. +- `replace` and `rollup.replace`: compile-time replacements in the bundled entries. +- `sourcemap`: `true` emits source maps, like `--sourcemap`. +- The `build:before`, `rollup:done`, and `build:done` hooks. + +`mkdist:*` hooks are ignored with a warning, and a few other options are accepted at their defaults. Any other option fails the build, with a list of each one and the file it comes from. To type the file, import `defineBuildConfig` from `@nuxt/module-builder`: + +```ts [build.config.ts] +import { defineBuildConfig } from '@nuxt/module-builder' + +export default defineBuildConfig({ + hooks: { + 'build:done'(ctx) { + console.log(`Built ${ctx.options.name} into ${ctx.options.outDir}`) + }, + }, +}) +``` + +Move `entries` and string `externals` to the `build` field of `package.json`, and delete the file once nothing else is left in it. See [Build configuration](/docs/guide/modules/module-builder/upgrade-v2#build-configuration) in the upgrade guide for how each option is applied, and for the options that fail the build. diff --git a/docs/4.typescript.md b/docs/4.typescript.md new file mode 100644 index 00000000..175d16f9 --- /dev/null +++ b/docs/4.typescript.md @@ -0,0 +1,121 @@ +--- +title: TypeScript +description: Set up the module's `tsconfig.json`, and generate correct declarations for `dist`. +--- + +A module has two TypeScript setups: one for the module itself, and one for its playground. This page covers both, and how the build generates the declarations in `dist` from the first. + +## The module's `tsconfig.json` + +The module root has a `tsconfig.json` of its own, which extends the `.nuxt/tsconfig.json` that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) generates there: + +```json [tsconfig.json] +{ + "extends": "./.nuxt/tsconfig.json", + "exclude": ["dist", "node_modules", "playground"] +} +``` + +This single tsconfig covers `src/module.ts` and `src/runtime/` alike. Your editor, your type check, and the declarations that `nuxt-module-build build` generates all read it, so they see the same types. + +The `.nuxt` in the module root types the module as Nuxt sees it with the module installed alone, at its default options, with auto-imports disabled. It's separate from the playground's `.nuxt`, which reflects the playground's configuration and any other modules it installs. + +Exclude `playground` so the playground's files are typed by its own tsconfig. Add any other directory that isn't part of the module, such as `docs`, to `exclude` too. + +## The playground's `tsconfig.json` + +The playground is a Nuxt app, so its `tsconfig.json` is set up like any other Nuxt app's, against the `.nuxt` that `nuxt prepare playground` generates. The starter uses: + +```json [playground/tsconfig.json] +{ + "extends": "./.nuxt/tsconfig.json" +} +``` + +A playground can also use the project references that Nuxt generates for an app. See [TypeScript](/docs/guide/concepts/typescript) in the Nuxt docs. + +To type-check the module and the playground, run the type check once in each: + +```json [package.json] +{ + "scripts": { + "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit" + } +} +``` + +## Monorepos + +In a monorepo, give the module its own `tsconfig.json` as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Move any `compilerOptions` the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check and to its declarations. + +The tsconfig that covers your module might extend or reference another app's `.nuxt/tsconfig.json` instead. In that case, the build generates declarations with the module's `./.nuxt/tsconfig.json` plus that tsconfig's own `compilerOptions`, and prints a note. See [Module tsconfig](/docs/guide/modules/module-builder/upgrade-v2#module-tsconfig) in the upgrade guide. + +## Declarations + +`nuxt-module-build build` generates declarations from your module's own files, with the module's tsconfig: + +- The module entry and every other bundled entry, with TypeScript, or with oxc when `isolatedDeclarations` is set. +- Every script in the runtime directory and other directory entries, with TypeScript. +- Every `.vue` file, with `@vue/language-core`, the same tooling that `vue-tsc` uses. + +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. Files that your module's sources import are still followed, 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. + +### Errors that fail the build + +An error that leaves a declaration missing or wrong fails the build. The most common is an export whose inferred type refers to a package your module can't import by name (TS2742, TS2883, or TS4023). Give each export it lists an explicit type annotation. In this example, the handler's arguments are omitted: + +```ts +// before +export const handler = defineCachedHandler(...) + +// after +export const handler: ReturnType = defineCachedHandler(...) +``` + +Syntax errors, and files for which no declaration can be emitted, fail the build as well. See [Portability errors](/docs/guide/modules/module-builder/upgrade-v2#portability-errors) in the upgrade guide for more examples. + +### Type errors reported as warnings + +Every other type error, such as a wrong argument type, is reported as a warning. The build prints one warning per directory, with the number of errors and the first three. Run your module's own type check to see them all. + +Build-time aliases (`#build/*`, `#internal/*`, and other paths into `.nuxt`) are typed as `any` while declarations are generated. So are they in `dist`: an export whose type is inferred through one of them is declared as `any`. Annotate such an export with a type that refers to it by name. The type then resolves against the `.nuxt` of the app that installs the module. See [Other type errors](/docs/guide/modules/module-builder/upgrade-v2#other-type-errors) in the upgrade guide. + +### `isolatedDeclarations` + +With `isolatedDeclarations: true` in the module's tsconfig, the module entry's declarations come from oxc. Every export then needs an explicit type, including the module definition: + +```ts [src/module.ts] +import { defineNuxtModule } from '@nuxt/kit' +import type { NuxtModule } from '@nuxt/schema' + +export interface ModuleOptions { + apiKey: string +} + +const module: NuxtModule = defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() {}, +}) + +export default module +``` + +Without `isolatedDeclarations`, the build prints a reminder once per run outside CI. Both settings work. + +## Recommended compiler options + +`erasableSyntaxOnly` makes the type check report syntax that Node's type stripping can't run, such as `enum` and parameter properties. The stub build and `prepare` load such syntax only when `tsdown` is installed: + +```json [tsconfig.json] +{ + "extends": "./.nuxt/tsconfig.json", + "compilerOptions": { + "erasableSyntaxOnly": true + }, + "exclude": ["dist", "node_modules", "playground"] +} +``` + +The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension in module code type-check without further settings. diff --git a/docs/5.output.md b/docs/5.output.md new file mode 100644 index 00000000..4cd10267 --- /dev/null +++ b/docs/5.output.md @@ -0,0 +1,111 @@ +--- +title: Build Output +description: The files that `nuxt-module-build build` writes to `dist`. +--- + +A module with `src/module.ts`, `src/runtime/`, and a `./src/utils` [entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into: + +```bash +dist/ +โ”œโ”€โ”€ module.mjs # src/module.ts, bundled +โ”œโ”€โ”€ module.d.mts # its declarations +โ”œโ”€โ”€ module.json # the module's meta +โ”œโ”€โ”€ types.d.mts # the types that `exports["."].types` points at +โ”œโ”€โ”€ utils.mjs # src/utils.ts, bundled +โ”œโ”€โ”€ utils.d.mts +โ””โ”€โ”€ runtime/ # src/runtime/, file by file +``` + +The output is ES modules only. Pass `--sourcemap` to emit a source map next to every script. + +## `module.mjs` + +`src/module.ts`, bundled with tsdown. It's compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. + +Imports of the runtime directory, and of other directory entries, point at their output in `dist` and aren't bundled. See [Configuration](/docs/guide/modules/module-builder/configuration#bundled-entries) for the packages that stay external. + +## `module.json` + +The module's meta. It contains the `meta` of the module definition, and the versions of `@nuxt/module-builder` and `tsdown` that built it. When the definition doesn't set `name` or `version`, they come from `package.json`. The build loads `dist/module.mjs` to read it. + +```json [dist/module.json] +{ + "name": "my-module", + "configKey": "myModule", + "version": "1.0.0", + "builder": { + "@nuxt/module-builder": "2.0.0", + "tsdown": "0.23.7" + } +} +``` + +## `types.d.mts` + +The types of the package's root export. It re-exports everything `module.d.mts` exports, and adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: + +```ts [dist/types.d.mts] +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 { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, default } from './module.mjs' +``` + +When `src/module.ts` doesn't export `ModuleOptions`, `types.d.mts` infers it from the default export. + +## Runtime files + +Every file under `src/runtime/` is emitted under `dist/runtime/` with its name intact, apart from the extension: + +| Source | Output | +|---|---| +| Scripts: `.ts`, `.mts`, `.cts`, `.js`, `.mjs`, `.cjs` | `.js`, with a `.d.ts` declaration | +| `.tsx`, `.jsx` | `.jsx`, with types stripped and the JSX kept, and a `.d.ts` declaration. See [JSX](#jsx). | +| `.vue` | `.vue`, with TypeScript stripped, and `.d.vue.ts` and `.vue.d.ts` declarations | +| `.css` | `.css`, with nesting flattened, vendor prefixes added for the project's browserslist targets, and minified | +| `.scss`, `.sass` | `.css`, compiled with your module's `sass` or `sass-embedded`. Partials (`_name.scss`) aren't emitted. | +| Anything else, including `.d.ts` | Copied as it is | + +Test and story files (`*.spec.ts`, `*.test.ts`, `*.stories.ts`, and their other script extensions) are left out. + +Scripts are transpiled with oxc, one file at a time. Each keeps its own imports and exports: + +- Relative imports get the emitted extension: `../utils/merge` becomes `../utils/merge.js`, and `./styles.scss` becomes `./styles.css`. +- Non-relative imports (`#imports`, `#build/*`, and packages) are kept as written. +- Imports used only as types are removed. + +A relative import of a file outside `src/runtime/` emits that file too, where the import points: `src/shared/x.ts` becomes `dist/shared/x.js`. When that would leave `dist` or take the name of another output, it's emitted under `dist/_external/` instead. A file that is only imported for its types gets a declaration and no script. + +`.css` `@import` statements are kept as written. Postcss configuration isn't applied to runtime stylesheets; process them in the Nuxt app, or before the build. + +Other [directory entries](/docs/guide/modules/module-builder/configuration#directory-entries) are emitted in the same way, under their own `outDir`, with `.mjs` and `.d.mts` unless their `ext` is `js`. In every directory, a file whose JSX is kept is emitted as `.jsx` with a `.d.ts`. + +### JSX + +`.tsx` and `.jsx` files keep their JSX, so the app that installs the module compiles it with its own Vue JSX plugin. Refer to these files without an extension, as in `resolver.resolve('./runtime/components/Banner')`. The path then resolves to the `.tsx` source in development and to the `.jsx` output once the module is published. + +Nitro and Node don't transform files in `node_modules`. JSX that runs there is compiled to `vue/jsx-runtime` calls instead, and the file is emitted as `.js`. This applies to: + +- Scripts under a `server/` directory. +- Runtime files that these scripts or a bundled entry, such as `src/module.ts`, import values from through relative paths. + +An import through an alias or through the module's own package name isn't followed. + +## Runtime declarations + +Declarations of runtime files are rewritten so they resolve in the app that installs the module: + +- Relative imports get the extension of the file they resolve to, for `node16` and `nodenext` module resolution. +- `#app` imports become `nuxt/app`. +- Other Nuxt aliases, such as `#build/*` and `#imports`, are kept. They resolve against the `.nuxt` of the app that installs the module. + +See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) for how declarations are generated, and the errors that fail the build. diff --git a/docs/6.exports.md b/docs/6.exports.md new file mode 100644 index 00000000..e8dd5bab --- /dev/null +++ b/docs/6.exports.md @@ -0,0 +1,112 @@ +--- +title: Exports +description: Publish more entry points than the module itself, such as utilities, composables, and components. +--- + +The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. Anything else you want users to import by name needs its own subpath in the `exports` of `package.json`. + +## Bundled entries + +A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into `dist/.mjs` and `dist/.d.mts`. Export it with both: + +```json [package.json] +{ + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + }, + "./utils": { + "types": "./dist/utils.d.mts", + "import": "./dist/utils.mjs" + } + }, + "typesVersions": { + "*": { + ".": ["./dist/types.d.mts"], + "utils": ["./dist/utils.d.mts"] + } + }, + "build": { + "entries": ["./src/utils"] + } +} +``` + +Users then import it as `my-module/utils`. A bundled entry suits code that runs alongside the module, such as helpers for `nuxt.config` or for other modules. + +`typesVersions` is only read by TypeScript's `node10` module resolution, which ignores `exports`. Write each path in full, with its `.d.mts` extension: `node10` doesn't probe for `.d.mts` when the extension is left out. + +## Runtime files + +Files in `src/runtime/` can be exported too, from their output in `dist/runtime/`. This lets an app import them explicitly, as well as through whatever the module registers for auto-import. + +To export a set of components, re-export them from an `index.ts` in the same directory: + +```ts [src/runtime/components/index.ts] +export { default as Button } from './Button.vue' +export { default as Card } from './Card.vue' +``` + +Then point an export at its output: + +```json [package.json] +{ + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + }, + "./components": { + "types": "./dist/runtime/components/index.d.ts", + "import": "./dist/runtime/components/index.js" + } + }, + "typesVersions": { + "*": { + ".": ["./dist/types.d.mts"], + "components": ["./dist/runtime/components/index.d.ts"] + } + } +} +``` + +An app that installs the module can now import each component with its full type: + +```vue [app.vue] + + + +``` + +To register the same components for auto-import, pass the index to `addComponentExports` from `@nuxt/kit`. Each named export becomes a component, prefixed with `prefix`: + +```ts [src/module.ts] +import { addComponentExports, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addComponentExports({ + filePath: resolver.resolve('./runtime/components/index'), + prefix: 'My', + }) + }, +}) +``` + +`` and `` are then available without an import. Composables and utilities work the same way: export them from an index, and register them with `addImports` or `addImportsDir`. + +::note +A [stub build](/docs/guide/modules/module-builder/commands#build-stub) doesn't write `dist/runtime/`. These subpaths resolve once the module has been built with `nuxt-module-build build`. +:: + +## Importing your own exports + +Runtime code and module code can import the module's own package name, such as `my-module/utils`. These imports are never bundled, and resolve to the published files in the app that installs the module. While the build generates declarations, they resolve to your sources instead, so they type-check before `dist` exists. diff --git a/docs/7.transpile-dir.md b/docs/7.transpile-dir.md new file mode 100644 index 00000000..9dfbaf69 --- /dev/null +++ b/docs/7.transpile-dir.md @@ -0,0 +1,82 @@ +--- +title: Transpiling a Directory +description: Use the `transpileDir` rolldown plugin to transpile a directory file by file in any tsdown or rolldown build. +--- + +The runtime build is a rolldown plugin, `transpileDir`, exported from `@nuxt/module-builder/rolldown`. Use it in any tsdown or rolldown build that transpiles a directory file by file instead of bundling it: + +```ts [tsdown.config.ts] +import { defineConfig } from 'tsdown' +import { transpileDir } from '@nuxt/module-builder/rolldown' + +export default defineConfig({ + entry: ['src/index.ts'], + plugins: [ + transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }), + ], +}) +``` + +Every file under `srcDir` is emitted under `outBase` in the build's output directory, with its name intact apart from the extension. Scripts become `.js` (or `.mjs`), `.tsx` and `.jsx` files become `.jsx` while their JSX is preserved, and compiled Sass becomes `.css`. Test and story files are excluded by default. + +Scripts are transpiled with oxc and keep their imports as written, apart from relative imports, which get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. + +Scripts are transpiled with the `transform` of the installed `rolldown`, which `tsdown` depends on. In a build without it, install `rolldown` or pass a `transform`. + +## Options + +| Option | Default | Description | +|---|---|---| +| `srcDir` | | The directory whose files are transpiled one by one. | +| `outBase` | the output directory | Where the outputs go, relative to the build's output directory. | +| `cwd` | the build's `cwd` | The project root: where `srcDir` is resolved, the tsconfig search starts, and `node_modules` is read. | +| `include` | every file | Globs of files to include, relative to `srcDir`. | +| `exclude` | test and story files | Globs of files to exclude. | +| `extension` | `'js'` | The extension of emitted scripts: `'js'` or `'mjs'`. Declarations follow, as `.d.ts` or `.d.mts`. | +| `tsconfig` | the nearest above `cwd` | The tsconfig to compile with, or `false` for none. | +| `paths` | | `paths` added to the tsconfig's when generating declarations. | +| `jsx` | `'preserve'` | JSX compilation for `.tsx` and `.jsx` files, or a function of the source path that returns it. `'preserve'` emits them as `.jsx` with types stripped, next to a `.d.ts`. | +| `transform` | the one of the installed `rolldown` | The oxc `transform` to use. | +| `sourcemap` | `false` | Emit source maps next to scripts. | +| `declaration` | `true` | Generate declarations. | +| `stylesheets` | `true` | Process `.css` with lightningcss and compile Sass. `false` copies stylesheets as they are. | +| `vue` | enabled | Options for `.vue` files, or `false` to leave them out. | +| `resolveExternal` | | Decides what happens to relative imports that resolve outside `srcDir`. | + +The options are documented in full on the `TranspileDirOptions` type. + +## Imports outside `srcDir` + +By default, a relative import that resolves outside `srcDir` is kept as written. `resolveExternal` is called for each one. Its third argument describes the import: the absolute path of the file, and whether the import is for its value or only its type. It also gives the paths where the importer and the file would be emitted. It returns one of: + +- A string: the specifier to write instead. +- `{ mirror: 'value' }` or `{ mirror: 'type' }`: emit the file alongside the directory, as a script and declaration, or as a declaration only. An `output` path, relative to the output directory, overrides where it's emitted. +- `undefined`: keep the specifier as written. + +```ts [tsdown.config.ts] +transpileDir({ + srcDir: 'src/runtime', + outBase: 'runtime', + resolveExternal: (_specifier, _importer, { kind }) => ({ mirror: kind }), +}) +``` + +## A build with nothing to bundle + +A build that only transpiles directories can pass `emptyEntry`, from the same export, as its `entry`. `transpileDir` removes its chunk from the output: + +```ts [tsdown.config.ts] +import { defineConfig } from 'tsdown' +import { emptyEntry, transpileDir } from '@nuxt/module-builder/rolldown' + +export default defineConfig({ + entry: emptyEntry, + plugins: [ + transpileDir({ srcDir: 'src' }), + ], +}) +``` + +## Type errors + +Errors that would leave a declaration missing or wrong fail the build. Other type errors are reported as one warning per directory. Its `pluginCode` equals the `TYPE_ERRORS_WARNING` constant, exported from `@nuxt/module-builder/rolldown`, so an `onLog` handler can filter the warning or turn it into an error. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..08dd7c2f --- /dev/null +++ b/docs/index.md @@ -0,0 +1,86 @@ +--- +title: Module Builder +description: Build and publish Nuxt modules with `@nuxt/module-builder`. +navigation: + title: Getting Started +--- + +`@nuxt/module-builder` builds a Nuxt module for publishing to npm. It bundles the module entry with [tsdown](https://tsdown.dev) and transpiles the runtime directory file by file. It also generates type declarations against the module's own `.nuxt`, and writes the type shims that give `nuxt.config` autocompletion for the module's options. + +The builder works with the layout of the [module starter](https://github.com/nuxt/starter/tree/module) and needs no configuration for it. To learn how to write the module itself (its definition, hooks, and the `@nuxt/kit` utilities), read the [Module Author Guide](/docs/guide/modules). + +## Requirements + +To build a module, you need: + +- Node `^22.18.0 || >=24.0.0`. +- `tsdown` and `typescript` (`^5.9.3 || ^6.0.0`), which are peer dependencies of `@nuxt/module-builder`. +- `nuxt`, which provides the `@nuxt/cli` that `nuxt-module-build prepare` runs. + +To use a module built with it, an app needs Nuxt 3 or later. The module entry is compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. + +## Quick start + +Create a module from the starter: + +::code-group{sync="pm"} + +```bash [npm] +npm create nuxt -- -t module my-module +``` + +```bash [yarn] +yarn create nuxt -t module my-module +``` + +```bash [pnpm] +pnpm create nuxt -t module my-module +``` + +```bash [bun] +bun create nuxt --template=module my-module +``` + +:: + +Then install its dependencies and prepare it for development: + +```bash +cd my-module +npm install +npm run dev:prepare +``` + +`dev:prepare` stubs the module's `dist` directory and generates the `.nuxt` directories that type the module and its playground. See [Commands](/docs/guide/modules/module-builder/commands) for what each step does. + +## Manual installation + +Add the builder and its peer dependencies to an existing module: + +```bash +pnpm add -D @nuxt/module-builder tsdown@^0.23.7 typescript nuxt +``` + +Then add the scripts that build the module before publishing and prepare it for development: + +```json [package.json] +{ + "scripts": { + "prepack": "nuxt-module-build build", + "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground" + } +} +``` + +Your module also needs the `exports` and `files` fields described in [Project structure](/docs/guide/modules/module-builder/project-structure#packagejson), and a `tsconfig.json` as described in [TypeScript](/docs/guide/modules/module-builder/typescript). + +## Next steps + +- [Project structure](/docs/guide/modules/module-builder/project-structure): the files the builder reads. +- [Commands](/docs/guide/modules/module-builder/commands): `build`, `build --stub`, and `prepare`. +- [Configuration](/docs/guide/modules/module-builder/configuration): extra entries and directories. +- [TypeScript](/docs/guide/modules/module-builder/typescript): the module's `tsconfig.json` and its declarations. +- [Build output](/docs/guide/modules/module-builder/output): what ends up in `dist`. +- [Exports](/docs/guide/modules/module-builder/exports): subpath exports, including runtime components. +- [Transpiling a directory](/docs/guide/modules/module-builder/transpile-dir): the `transpileDir` rolldown plugin. +- [Upgrading to v2](/docs/guide/modules/module-builder/upgrade-v2): moving a module from v1. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index febbc74a..3d5b9e26 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -1,4 +1,7 @@ -# Upgrading to @nuxt/module-builder v2 +--- +title: Upgrading to v2 +description: Move a Nuxt module from v1 to v2 of `@nuxt/module-builder`, which builds with tsdown. +--- This guide takes a Nuxt module from v1 to v2 of the module builder. In v2, `@nuxt/module-builder` builds your module with [tsdown](https://tsdown.dev) instead of unbuild. The CLI, the project layout (`src/module.ts` and `src/runtime/`), and the output of your build stay the same. @@ -6,7 +9,7 @@ Most modules upgrade by running the build and following its output. Every messag ## Node engines -v2 requires Node `^22.18.0 || ^24.11.0 || >=26.0.0`. Use Node 22.18+, 24.11+, or 26+ locally and in CI: +v2 requires Node `^22.18.0 || >=24.0.0`. Use Node 22.18+ or 24+ locally and in CI: ```yaml # .github/workflows/ci.yml @@ -293,7 +296,7 @@ The `.d.ts` declarations of bundled entries aren't generated either, so `typesVe ### mkdist options -Runtime files are transpiled with oxc, one file at a time. Options that configured mkdist have no equivalent and fail the build: `esbuild`, `pattern`, `declaration` on an entry, and `format`. Remove them. Postcss plugins passed through `mkdist:entry:options` are ignored with a warning. Replace that processing as described in [Runtime stylesheets](#runtime-stylesheets). On a directory entry, `ext` (`mjs` or `js`) is applied, and `addRelativeDeclarationExtensions` is accepted and ignored: relative imports in declarations always get their extension. +Runtime files are transpiled with oxc, one file at a time. Options that configured mkdist have no equivalent and fail the build: `esbuild`, `pattern`, and `format`. Remove them. `declaration` on an entry is accepted and ignored, like the top-level option. Postcss plugins passed through `mkdist:entry:options` are ignored with a warning. Replace that processing as described in [Runtime stylesheets](#runtime-stylesheets). On a directory entry, `ext` (`mjs` or `js`) is applied, and `addRelativeDeclarationExtensions` is accepted and ignored: relative imports in declarations always get their extension. ```ts // before @@ -464,7 +467,7 @@ import type { NuxtApp } from '#app' addPlugin(resolver.resolve('./runtime/plugin')) ``` -Fix the list before you run `prepare` or `dev:prepare`: until it's empty, `prepare` stops and `.nuxt` isn't generated, so the module's type check and editor types have nothing to extend. +Fix the list before you run `prepare` or `dev:prepare`. Until it's empty, `prepare` stops and doesn't generate `.nuxt`. The module's type check and editor types then have nothing to extend. ## Declaration errors @@ -508,7 +511,7 @@ If the type check reports the same errors, fix them there. If it passes, the war Its errors come from build-time aliases (`#build/*`, `#internal/*`, and other paths into `.nuxt/`), which are typed as `any` while declarations are generated. The types in your module's `.nuxt` also reflect the module's default options. Code that only type-checks under a playground's configuration (a provider the playground enables, for example) warns here as well. An explicit annotation on the export removes that warning. -Those aliases are `any` in the emitted declarations too. An export whose type is inferred through one of them is declared as `any`, or as `string | number | symbol` for a key type. This includes a module's own generated alias, such as `#mdc-highlighter`. Annotate such an export with a type that refers to it by name, such as a component's props type or a type imported from the alias. The type then resolves against the consuming app's `.nuxt`: +Those aliases are `any` in the emitted declarations too. An export whose type is inferred through one of them is declared as `any`, or as `string | number | symbol` for a key type. This includes a module's own generated alias, such as `#mdc-highlighter`. Annotate such an export with a type that refers to it by name. That can be a component's props type, or a type imported from the alias. The type then resolves against the `.nuxt` of the app that installs the module: ```ts import type { ComputedRef } from 'vue' @@ -521,13 +524,13 @@ export function useButtonSize(props: ButtonProps) { return computed(() => props.size ?? theme.defaultVariants.size) } -// after: `ButtonProps['size']` is kept by name and resolves against the consuming app's `.nuxt` +// after: `ButtonProps['size']` is kept by name and resolves against the app's own `.nuxt` export function useButtonSize(props: ButtonProps): ComputedRef { return computed(() => props.size ?? theme.defaultVariants.size) } ``` -Routes your module registers with `addServerHandler` are typed from the module's own `.nuxt` (see [Module tsconfig](#module-tsconfig)). A composable that returns a `useFetch` or `$fetch` result for one of them is declared with the handler's response type. The response of any other route, one the playground or the consuming app defines, is typed `unknown`. To publish a precise type, type those calls or annotate the export: +Routes your module registers with `addServerHandler` are typed from the module's own `.nuxt` (see [Module tsconfig](#module-tsconfig)). A composable that returns a `useFetch` or `$fetch` result for one of them is declared with the handler's response type. The response of any other route, one the playground or the app that installs the module defines, is typed `unknown`. To publish a precise type, type those calls or annotate the export: ```ts import type { AsyncData, NuxtError } from 'nuxt/app' @@ -579,7 +582,7 @@ Stylesheets under `src/runtime` are processed with lightningcss instead of postc ## Runtime output -Each file under `src/runtime` is still emitted under `dist/runtime` with its name intact: scripts as `.js` with a `.d.ts`, and `.vue` files as `.vue` with a `.vue.d.ts`. Check these differences when a runtime file doesn't behave as before: +Each file under `src/runtime` is still emitted under `dist/runtime` with its name intact. Scripts become `.js` with a `.d.ts`, and `.vue` files stay `.vue` with a `.vue.d.ts`. Check these differences when a runtime file doesn't behave as before: - Relative imports get the emitted extension (`../utils/merge` becomes `../utils/merge.js`). Non-relative specifiers (`#imports`, `#build/*`, and dependencies) are kept as written. - Imports used only as types are removed from the JavaScript output. @@ -760,7 +763,7 @@ pnpm remove unbuild Follow these steps in order to upgrade a module. Each step is mechanical until the build runs. Use your module's own package manager where `pnpm` is written. -1. Use Node 22.18+, 24.11+, or 26+ locally and in CI. +1. Use Node 22.18+ or 24+ locally and in CI. 2. Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`, then `pnpm remove unbuild` (and `mkdist` and `jiti`, if they only served the builder). Do this before step 3. 3. Move the options of `build.config.ts` and of the `build` or `unbuild` field of `package.json` into `builder()` in a `tsdown.config.ts`, as described in [Moving from build.config.ts](#moving-from-buildconfigts), including directory entries such as `{ input: 'src/x/', outDir: 'dist/x' }`. Then delete `build.config.ts` and remove the field. A module without options still gets a `tsdown.config.ts` with `plugins: [builder()]`, so that `tsdown` builds it. 4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Set the top-level `types` field to `./dist/types.d.mts`, or remove it. Give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). diff --git a/src/build/guide.ts b/src/build/guide.ts index d1b8c88f..2fdfabf4 100644 --- a/src/build/guide.ts +++ b/src/build/guide.ts @@ -1,34 +1,38 @@ const GUIDE_URL = 'https://github.com/nuxt/module-builder/blob/main/docs/upgrade-v2.md' -export type GuideSection - = | 'node-engines' - | 'install-tsdown' - | 'build-configuration' - | 'tsdown-config' - | 'options-builder-sets' - | 'hooks-in-a-tsdown-config' - | 'moving-from-buildconfigts' - | 'unsupported-build-options' - | 'hooks' - | 'rollup-options' - | 'commonjs-output' - | 'mkdist-options' - | 'other-options' - | 'declaration-paths' - | 'modulecjs' - | 'the-types-field' - | 'paths-the-build-does-not-produce' - | 'typesversions-paths' - | 'stub-builds' - | 'declaration-errors' - | 'portability-errors' - | 'other-type-errors' - | 'isolated-declarations' - | 'preparing-nuxt' - | 'module-tsconfig' - | 'output-directory' - | 'publishing-source-exports' - | 'module-code-loads-with-node' +/** The sections of the upgrade guide that build messages link to, by heading anchor. */ +export const GUIDE_SECTIONS = [ + 'node-engines', + 'install-tsdown', + 'build-configuration', + 'tsdown-config', + 'options-builder-sets', + 'hooks-in-a-tsdown-config', + 'moving-from-buildconfigts', + 'unsupported-build-options', + 'hooks', + 'rollup-options', + 'commonjs-output', + 'mkdist-options', + 'other-options', + 'declaration-paths', + 'modulecjs', + 'the-types-field', + 'paths-the-build-does-not-produce', + 'typesversions-paths', + 'stub-builds', + 'declaration-errors', + 'portability-errors', + 'other-type-errors', + 'isolated-declarations', + 'preparing-nuxt', + 'module-tsconfig', + 'output-directory', + 'publishing-source-exports', + 'module-code-loads-with-node', +] as const + +export type GuideSection = typeof GUIDE_SECTIONS[number] /** The URL of a section of the upgrade guide. */ export function guide(section: GuideSection) { diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 21db8115..7bdbcebb 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -24,7 +24,7 @@ import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, checkMissingPaths, ch import { importsKeyFor, publishedPackage, sourcePathsPackError, unpublishableImportsError, unpublishablePathsError } from '../src/build/package.ts' import { writeSourceTypes } from '../src/build/types.ts' import ts from 'typescript' -import { guide } from '../src/build/guide.ts' +import { GUIDE_SECTIONS, guide } from '../src/build/guide.ts' import { findModuleCodeIssues } from '../src/build/loader.ts' import type { ModuleCodeIssue } from '../src/build/loader.ts' import { MISSING_TSDOWN_HINT } from '../src/commands/build.ts' @@ -308,6 +308,15 @@ describe('translateBuildConfig', () => { }) }) +describe('upgrade guide', () => { + it('should have a heading for every section that build messages link to', async () => { + const markdown = await readFile(new URL('../docs/upgrade-v2.md', import.meta.url), 'utf8') + const anchors = [...markdown.replace(/^```.*\n[\s\S]*?^```/gm, '').matchAll(/^#{2,6} (.+)$/gm)] + .map(([, heading]) => heading!.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu, '').replaceAll(' ', '-')) + expect(GUIDE_SECTIONS.filter(section => !anchors.includes(section))).toEqual([]) + }) +}) + describe('hints', () => { it('should link the missing tsdown hint to the upgrade guide', () => { expect(MISSING_TSDOWN_HINT).toMatch(new RegExp(`pnpm add -D tsdown@"\\^[\\d.]+"\`\\. ${guide('install-tsdown')}$`)) From 05a4701eae5b356dabe46a02f7a10296124b15b9 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 00:02:42 +0000 Subject: [PATCH 02/28] docs: set the root `types` field for node10 consumers --- docs/1.project-structure.md | 10 ++-------- docs/6.exports.md | 6 +++--- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 35b363df..40d6a470 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -127,13 +127,7 @@ A minimal `package.json` for a module: } }, "main": "./dist/module.mjs", - "typesVersions": { - "*": { - ".": [ - "./dist/types.d.mts" - ] - } - }, + "types": "./dist/types.d.mts", "files": [ "dist" ], @@ -155,7 +149,7 @@ A minimal `package.json` for a module: ``` - `exports["."].types` points at `dist/types.d.mts`, which re-exports the module's types along with the [augmentations](#srcmodulets) above. -- `typesVersions` resolves the same file for consumers that use TypeScript's `node10` module resolution, which ignores `exports`. +- `types` resolves the same file for consumers that use TypeScript's `node10` module resolution, which ignores `exports`. For subpath exports, `node10` reads `typesVersions` instead, as described in [Exports](/docs/guide/modules/module-builder/exports). - `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. Any other package that the module entry imports, such as a `devDependency`, is bundled into it. After every build, the builder checks the paths in `exports`, `main`, `module`, `types`, and `typesVersions`, and warns about any that the build didn't produce. diff --git a/docs/6.exports.md b/docs/6.exports.md index e8dd5bab..27beb3d3 100644 --- a/docs/6.exports.md +++ b/docs/6.exports.md @@ -21,9 +21,9 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri "import": "./dist/utils.mjs" } }, + "types": "./dist/types.d.mts", "typesVersions": { "*": { - ".": ["./dist/types.d.mts"], "utils": ["./dist/utils.d.mts"] } }, @@ -35,7 +35,7 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri Users then import it as `my-module/utils`. A bundled entry suits code that runs alongside the module, such as helpers for `nuxt.config` or for other modules. -`typesVersions` is only read by TypeScript's `node10` module resolution, which ignores `exports`. Write each path in full, with its `.d.mts` extension: `node10` doesn't probe for `.d.mts` when the extension is left out. +`types` and `typesVersions` are only read by TypeScript's `node10` module resolution, which ignores `exports`. `types` covers the root import, and `typesVersions` covers each subpath. Write each path in full, with its `.d.mts` extension: `node10` doesn't probe for `.d.mts` when the extension is left out. ## Runtime files @@ -62,9 +62,9 @@ Then point an export at its output: "import": "./dist/runtime/components/index.js" } }, + "types": "./dist/types.d.mts", "typesVersions": { "*": { - ".": ["./dist/types.d.mts"], "components": ["./dist/runtime/components/index.d.ts"] } } From 1b95309e33e2b6f5204876770717449bc4f2e2f7 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 00:02:52 +0000 Subject: [PATCH 03/28] =?UTF-8?q?docs:=20address=20comments=20=F0=9F=90=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/5.output.md | 2 +- docs/7.transpile-dir.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/5.output.md b/docs/5.output.md index 4cd10267..7fd580f2 100644 --- a/docs/5.output.md +++ b/docs/5.output.md @@ -42,7 +42,7 @@ The module's meta. It contains the `meta` of the module definition, and the vers ## `types.d.mts` -The types of the package's root export. It re-exports everything `module.d.mts` exports, and adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: +The types of the package's root export. It re-exports the default export of `module.d.mts`, and its other exports as types only. It also adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: ```ts [dist/types.d.mts] import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' diff --git a/docs/7.transpile-dir.md b/docs/7.transpile-dir.md index 9dfbaf69..667aed3c 100644 --- a/docs/7.transpile-dir.md +++ b/docs/7.transpile-dir.md @@ -21,7 +21,7 @@ Every file under `srcDir` is emitted under `outBase` in the build's output direc Scripts are transpiled with oxc and keep their imports as written, apart from relative imports, which get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. -Scripts are transpiled with the `transform` of the installed `rolldown`, which `tsdown` depends on. In a build without it, install `rolldown` or pass a `transform`. +By default, scripts are transpiled with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. `nuxt-module-build build` passes the `transform` of the `rolldown` that `tsdown` installs, so a module needs neither. ## Options From f14aa3119285f7f26bb0880fa51856215061be70 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 07:51:20 +0000 Subject: [PATCH 04/28] docs: add the `nuxt build-module` command page --- docs/2.commands.md | 2 +- docs/cli/build-module/index.md | 51 ++++++++++++++++++++++++++++++++++ test/unit.spec.ts | 21 +++++++++++++- 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 docs/cli/build-module/index.md diff --git a/docs/2.commands.md b/docs/2.commands.md index c87ce7f0..a9b748b7 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -10,7 +10,7 @@ links: `@nuxt/module-builder` installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. -[`nuxt build-module`](/docs/api/commands/build-module) from the Nuxt CLI runs the same builder. +The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. ## `build` diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md new file mode 100644 index 00000000..c51025a3 --- /dev/null +++ b/docs/cli/build-module/index.md @@ -0,0 +1,51 @@ +--- +title: 'nuxt build-module' +description: 'Build a Nuxt module for publishing, or prepare it for development, with `@nuxt/module-builder`.' +links: + - label: Source + icon: i-simple-icons-github + to: https://github.com/nuxt/module-builder/tree/main/src/commands + size: xs +--- + +```bash [Terminal] +npx nuxt build-module build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] [--stub] +npx nuxt build-module prepare [ROOTDIR] [--cwd=] +``` + +The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/module-builder`](/docs/guide/modules/module-builder) installs in your module. It's the same CLI as `nuxt-module-build`, with two subcommands. Without a subcommand, it runs `build` and prints a warning. + +## `build` + +Builds the module into `dist` for publishing. With `--stub`, it writes `dist` as re-exports of your sources instead, for development. See [`build`](/docs/guide/modules/module-builder/commands#build) and [`build --stub`](/docs/guide/modules/module-builder/commands#build-stub). + +### Arguments + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| Option | Default | Description | +|---|---|---| +| `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | +| `--outDir=` | `dist` | The output directory, relative to the module root. It's emptied before every build, so it must be inside the module. | +| `--sourcemap` | `false` | Emit a source map next to every script. | +| `--stub` | `false` | Write a stub build instead. | + +## `prepare` + +Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). + +### Arguments + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| Option | Default | Description | +|---|---|---| +| `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 7bdbcebb..92207b99 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -27,7 +27,8 @@ import ts from 'typescript' import { GUIDE_SECTIONS, guide } from '../src/build/guide.ts' import { findModuleCodeIssues } from '../src/build/loader.ts' import type { ModuleCodeIssue } from '../src/build/loader.ts' -import { MISSING_TSDOWN_HINT } from '../src/commands/build.ts' +import buildCommand, { MISSING_TSDOWN_HINT } from '../src/commands/build.ts' +import prepareCommand from '../src/commands/prepare.ts' const runtimeSrcDir = fileURLToPath(new URL('../example/src/runtime', import.meta.url)) const importer = fileURLToPath(new URL('../example/src/module.ts', import.meta.url)) @@ -317,6 +318,24 @@ describe('upgrade guide', () => { }) }) +describe('command docs', () => { + const commands = { build: buildCommand, prepare: prepareCommand } + + function documentedOptions(markdown: string, command: string) { + const section = markdown.split(/^## /m).find(section => section.startsWith(`\`${command}\`\n`))! + const options = section.split(/^### Options$/m)[1]!.split(/^#/m)[0]! + return Object.fromEntries([...options.matchAll(/^\| `--(\w+)(?:=[^`]*)?` \| (?:`([^`]*)`)? *\|/gm)].map(([, name, value]) => [name, value ?? ''])) + } + + it.each(['docs/2.commands.md', 'docs/cli/build-module/index.md'])('should list the options of each command in %s', async (file) => { + const markdown = await readFile(new URL(`../${file}`, import.meta.url), 'utf8') + for (const [name, command] of Object.entries(commands)) { + const args = Object.entries(command.args!).filter(([, arg]) => arg.type !== 'positional') + expect(documentedOptions(markdown, name)).toEqual(Object.fromEntries(args.map(([key, arg]) => [key, arg.default === undefined ? '' : String(arg.default)]))) + } + }) +}) + describe('hints', () => { it('should link the missing tsdown hint to the upgrade guide', () => { expect(MISSING_TSDOWN_HINT).toMatch(new RegExp(`pnpm add -D tsdown@"\\^[\\d.]+"\`\\. ${guide('install-tsdown')}$`)) From 015b329819a77b51debb8529e4a77f26aae6d180 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 08:33:55 +0000 Subject: [PATCH 05/28] docs: stop recommending node10 `types` and `typesVersions` --- docs/1.project-structure.md | 2 -- docs/6.exports.md | 14 +------------- docs/upgrade-v2.md | 2 +- 3 files changed, 2 insertions(+), 16 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 40d6a470..b7b10f10 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -127,7 +127,6 @@ A minimal `package.json` for a module: } }, "main": "./dist/module.mjs", - "types": "./dist/types.d.mts", "files": [ "dist" ], @@ -149,7 +148,6 @@ A minimal `package.json` for a module: ``` - `exports["."].types` points at `dist/types.d.mts`, which re-exports the module's types along with the [augmentations](#srcmodulets) above. -- `types` resolves the same file for consumers that use TypeScript's `node10` module resolution, which ignores `exports`. For subpath exports, `node10` reads `typesVersions` instead, as described in [Exports](/docs/guide/modules/module-builder/exports). - `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. Any other package that the module entry imports, such as a `devDependency`, is bundled into it. After every build, the builder checks the paths in `exports`, `main`, `module`, `types`, and `typesVersions`, and warns about any that the build didn't produce. diff --git a/docs/6.exports.md b/docs/6.exports.md index 27beb3d3..835dfd28 100644 --- a/docs/6.exports.md +++ b/docs/6.exports.md @@ -21,12 +21,6 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri "import": "./dist/utils.mjs" } }, - "types": "./dist/types.d.mts", - "typesVersions": { - "*": { - "utils": ["./dist/utils.d.mts"] - } - }, "build": { "entries": ["./src/utils"] } @@ -35,7 +29,7 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri Users then import it as `my-module/utils`. A bundled entry suits code that runs alongside the module, such as helpers for `nuxt.config` or for other modules. -`types` and `typesVersions` are only read by TypeScript's `node10` module resolution, which ignores `exports`. `types` covers the root import, and `typesVersions` covers each subpath. Write each path in full, with its `.d.mts` extension: `node10` doesn't probe for `.d.mts` when the extension is left out. +TypeScript reads the `types` condition of each export with the `bundler` and `node16` module resolution, which Nuxt apps use. `node10` module resolution ignores `exports`, and these docs don't cover it. If your module keeps a top-level `types` field or `typesVersions` for it, see [The types field](/docs/guide/modules/module-builder/upgrade-v2#the-types-field) and [typesVersions paths](/docs/guide/modules/module-builder/upgrade-v2#typesversions-paths) in the upgrade guide. ## Runtime files @@ -61,12 +55,6 @@ Then point an export at its output: "types": "./dist/runtime/components/index.d.ts", "import": "./dist/runtime/components/index.js" } - }, - "types": "./dist/types.d.mts", - "typesVersions": { - "*": { - "components": ["./dist/runtime/components/index.d.ts"] - } } } ``` diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 3d5b9e26..534d4976 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -766,7 +766,7 @@ Follow these steps in order to upgrade a module. Each step is mechanical until t 1. Use Node 22.18+ or 24+ locally and in CI. 2. Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`, then `pnpm remove unbuild` (and `mkdist` and `jiti`, if they only served the builder). Do this before step 3. 3. Move the options of `build.config.ts` and of the `build` or `unbuild` field of `package.json` into `builder()` in a `tsdown.config.ts`, as described in [Moving from build.config.ts](#moving-from-buildconfigts), including directory entries such as `{ input: 'src/x/', outDir: 'dist/x' }`. Then delete `build.config.ts` and remove the field. A module without options still gets a `tsdown.config.ts` with `plugins: [builder()]`, so that `tsdown` builds it. -4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Set the top-level `types` field to `./dist/types.d.mts`, or remove it. Give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). +4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. If it does, set `types` to `./dist/types.d.mts`, and give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). 5. Add `"erasableSyntaxOnly": true` to `tsconfig.json`, and rewrite any `enum`, `namespace`, parameter property, or `value` assertion the type check reports. 6. Make module code load with Node, as described in [Module code loads with Node](#module-code-loads-with-node): add the `.ts` extension to relative imports in `src/module.ts` and the files it imports by value, runtime files included (`./utils` becomes `./utils.ts`, `./dir` becomes `./dir/index.ts`), replace value imports through tsconfig `paths` aliases, and move value imports of `#app`, `#imports`, and `#build/*` into runtime files. Do this before step 8: `prepare` lists each problem and doesn't generate `.nuxt` until they're fixed. 7. If the runtime contains `.scss` or `.sass` files, run `pnpm add -D sass`. From 867ff88313aca4c895ade80c24a5afe832f412b7 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 08:49:51 +0000 Subject: [PATCH 06/28] test: normalise line endings when reading command docs --- test/unit.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 92207b99..fa17db71 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -328,7 +328,7 @@ describe('command docs', () => { } it.each(['docs/2.commands.md', 'docs/cli/build-module/index.md'])('should list the options of each command in %s', async (file) => { - const markdown = await readFile(new URL(`../${file}`, import.meta.url), 'utf8') + const markdown = (await readFile(new URL(`../${file}`, import.meta.url), 'utf8')).replaceAll('\r\n', '\n') for (const [name, command] of Object.entries(commands)) { const args = Object.entries(command.args!).filter(([, arg]) => arg.type !== 'positional') expect(documentedOptions(markdown, name)).toEqual(Object.fromEntries(args.map(([key, arg]) => [key, arg.default === undefined ? '' : String(arg.default)]))) From d74942a7bf262f699d343bb245d9bc04d8f87a13 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 13:59:17 +0000 Subject: [PATCH 07/28] docs: use `src/runtime/app` and `src/runtime/server` in examples --- docs/1.project-structure.md | 12 ++++++++---- docs/5.output.md | 2 +- docs/6.exports.md | 8 ++++---- docs/upgrade-v2.md | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index b7b10f10..394e17d7 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -3,13 +3,15 @@ title: Project Structure description: The files and directories that `@nuxt/module-builder` reads. --- -The builder expects the layout of the [module starter](https://github.com/nuxt/starter/tree/module): +The builder works with this layout: ```bash my-module/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ module.ts # the module definition โ”‚ โ””โ”€โ”€ runtime/ # code added to the app that installs the module +โ”‚ โ”œโ”€โ”€ app/ # components, composables, plugins, and other app code +โ”‚ โ””โ”€โ”€ server/ # server routes, middleware, and Nitro plugins โ”œโ”€โ”€ playground/ # a Nuxt app that installs the module โ”œโ”€โ”€ package.json โ””โ”€โ”€ tsconfig.json @@ -60,24 +62,26 @@ export default defineNuxtModule({ const resolver = createResolver(import.meta.url) nuxt.options.runtimeConfig.public.myModule = { apiKey: options.apiKey } - addPlugin(resolver.resolve('./runtime/plugin')) + addPlugin(resolver.resolve('./runtime/app/plugins/greeting')) }, }) ``` Relative imports in `src/module.ts`, and in every file it imports outside the runtime directories, carry the imported file's extension: `./utils.ts`, not `./utils`. The [stub build](/docs/guide/modules/module-builder/commands#build-stub) and [`prepare`](/docs/guide/modules/module-builder/commands#prepare) load these files with Node, which resolves relative specifiers as written. Type-only imports are exempt. -Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/plugin.ts` is emitted as `dist/runtime/plugin.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source in development, and the `.js` output once the module is published. +Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/app/plugins/greeting.ts` is emitted as `dist/runtime/app/plugins/greeting.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source in development, and the `.js` output once the module is published. ## `src/runtime/` Code that the module adds to the app: components, composables, plugins, server routes, stylesheets, and any other files. The module registers them from `setup()`, with utilities such as `addPlugin`, `addComponent`, or `addServerHandler`. +Put code for the app in `src/runtime/app/`, and code for the server in `src/runtime/server/`. Nuxt type-checks everything under `runtime/` in the app context except `runtime/server/`, which it type-checks in the server context. See [Augment Types](/docs/guide/modules/recipes-advanced#augment-types) in the Module Author Guide. + Each file is transpiled on its own into `dist/runtime/`, keeping its name and its imports. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. Files in the runtime directory can't rely on auto-imports, since Nuxt doesn't apply them to files in `node_modules`. Import what you use from `#imports`, or from the package that provides it: -```ts [src/runtime/composables/useGreeting.ts] +```ts [src/runtime/app/composables/useGreeting.ts] import { useRuntimeConfig } from '#imports' export function useGreeting() { diff --git a/docs/5.output.md b/docs/5.output.md index 7fd580f2..3ba17963 100644 --- a/docs/5.output.md +++ b/docs/5.output.md @@ -91,7 +91,7 @@ Other [directory entries](/docs/guide/modules/module-builder/configuration#direc ### JSX -`.tsx` and `.jsx` files keep their JSX, so the app that installs the module compiles it with its own Vue JSX plugin. Refer to these files without an extension, as in `resolver.resolve('./runtime/components/Banner')`. The path then resolves to the `.tsx` source in development and to the `.jsx` output once the module is published. +`.tsx` and `.jsx` files keep their JSX, so the app that installs the module compiles it with its own Vue JSX plugin. Refer to these files without an extension, as in `resolver.resolve('./runtime/app/components/Banner')`. The path then resolves to the `.tsx` source in development and to the `.jsx` output once the module is published. Nitro and Node don't transform files in `node_modules`. JSX that runs there is compiled to `vue/jsx-runtime` calls instead, and the file is emitted as `.js`. This applies to: diff --git a/docs/6.exports.md b/docs/6.exports.md index 835dfd28..e4c6821e 100644 --- a/docs/6.exports.md +++ b/docs/6.exports.md @@ -37,7 +37,7 @@ Files in `src/runtime/` can be exported too, from their output in `dist/runtime/ To export a set of components, re-export them from an `index.ts` in the same directory: -```ts [src/runtime/components/index.ts] +```ts [src/runtime/app/components/index.ts] export { default as Button } from './Button.vue' export { default as Card } from './Card.vue' ``` @@ -52,8 +52,8 @@ Then point an export at its output: "import": "./dist/module.mjs" }, "./components": { - "types": "./dist/runtime/components/index.d.ts", - "import": "./dist/runtime/components/index.js" + "types": "./dist/runtime/app/components/index.d.ts", + "import": "./dist/runtime/app/components/index.js" } } } @@ -82,7 +82,7 @@ export default defineNuxtModule({ const resolver = createResolver(import.meta.url) addComponentExports({ - filePath: resolver.resolve('./runtime/components/index'), + filePath: resolver.resolve('./runtime/app/components/index'), prefix: 'My', }) }, diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 534d4976..36415712 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -586,7 +586,7 @@ Each file under `src/runtime` is still emitted under `dist/runtime` with its nam - Relative imports get the emitted extension (`../utils/merge` becomes `../utils/merge.js`). Non-relative specifiers (`#imports`, `#build/*`, and dependencies) are kept as written. - Imports used only as types are removed from the JavaScript output. -- `.tsx` and `.jsx` files are emitted as `.jsx` with a `.d.ts`, with types stripped and the JSX kept, so the app compiles them with its own Vue JSX plugin. Pass paths to them without an extension, as in `resolver.resolve('./runtime/components/Foo')`. +- `.tsx` and `.jsx` files are emitted as `.jsx` with a `.d.ts`, with types stripped and the JSX kept, so the app compiles them with its own Vue JSX plugin. Pass paths to them without an extension, as in `resolver.resolve('./runtime/app/components/Foo')`. - JSX that runs in Nitro or Node is still compiled to `vue/jsx-runtime` calls, as neither transforms files in `node_modules`. This covers files under a `server/` directory, and runtime files that these or other bundled entries import values from through relative paths. An import through an alias or the module's own package name isn't followed. - A relative import of a file outside `src/runtime` is emitted where the import points (`src/shared/x.ts` becomes `dist/shared/x.js`). When that would leave `dist` or collide with another output, it's emitted under `dist/_external/` instead. A file that is only imported as a type gets a `.d.ts` and no script. - Your module's own package name is never bundled into `module.mjs`. Its `#` subpath imports from the `imports` of `package.json` are bundled. From 784d970e56fbaa14bd1f52a380b0f86c6f194edf Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 14:00:32 +0000 Subject: [PATCH 08/28] docs: add a page on developing and publishing a module --- README.md | 11 +-- docs/1.project-structure.md | 2 +- docs/2.commands.md | 24 +------ docs/3.develop-and-publish.md | 67 +++++++++++++++++++ ...{3.configuration.md => 4.configuration.md} | 0 docs/{4.typescript.md => 5.typescript.md} | 0 docs/{5.output.md => 6.output.md} | 0 docs/{6.exports.md => 7.exports.md} | 0 ...{7.transpile-dir.md => 8.transpile-dir.md} | 0 docs/index.md | 3 +- 10 files changed, 78 insertions(+), 29 deletions(-) create mode 100644 docs/3.develop-and-publish.md rename docs/{3.configuration.md => 4.configuration.md} (100%) rename docs/{4.typescript.md => 5.typescript.md} (100%) rename docs/{5.output.md => 6.output.md} (100%) rename docs/{6.exports.md => 7.exports.md} (100%) rename docs/{7.transpile-dir.md => 8.transpile-dir.md} (100%) diff --git a/README.md b/README.md index 3195fc3c..2e193904 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,12 @@ Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `types - [Getting started](./docs/index.md) - [Project structure](./docs/1.project-structure.md) - [Commands](./docs/2.commands.md): `build`, `build --stub`, and `prepare` -- [Configuration](./docs/3.configuration.md): extra entries, and the deprecated `build.config.ts` -- [TypeScript](./docs/4.typescript.md): the module's `tsconfig.json`, and its declarations -- [Build output](./docs/5.output.md) -- [Exports](./docs/6.exports.md): subpath exports, including runtime components -- [Transpiling a directory](./docs/7.transpile-dir.md): the `transpileDir` rolldown plugin +- [Develop and publish](./docs/3.develop-and-publish.md): the playground, and releasing to npm +- [Configuration](./docs/4.configuration.md): extra entries, and the deprecated `build.config.ts` +- [TypeScript](./docs/5.typescript.md): the module's `tsconfig.json`, and its declarations +- [Build output](./docs/6.output.md) +- [Exports](./docs/7.exports.md): subpath exports, including runtime components +- [Transpiling a directory](./docs/8.transpile-dir.md): the `transpileDir` rolldown plugin - [Upgrading to v2](./docs/upgrade-v2.md) For writing the module itself, read the [Nuxt Module Author Guide](https://nuxt.com/docs/guide/modules). diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 394e17d7..4ec0d8e8 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -112,7 +112,7 @@ export default defineNuxtConfig({ }) ``` -The playground therefore loads the module through its `package.json` `exports`, from `dist`. A [stub build](/docs/guide/modules/module-builder/commands#build-stub) points `dist` at your sources, so the playground runs them without a full build after every change. +The playground therefore loads the module through its `package.json` `exports`, from `dist`. A [stub build](/docs/guide/modules/module-builder/commands#build-stub) points `dist` at your sources, so the playground runs them without a full build after every change. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#working-in-the-playground). ## `package.json` diff --git a/docs/2.commands.md b/docs/2.commands.md index a9b748b7..b7963a2e 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -1,6 +1,6 @@ --- title: Commands -description: The `nuxt-module-build` commands, and how they fit together while you develop and publish a module. +description: The `nuxt-module-build` commands and their options. links: - label: Source icon: i-simple-icons-github @@ -10,7 +10,7 @@ links: `@nuxt/module-builder` installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. -The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. +The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. To see how the starter's scripts combine them, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). ## `build` @@ -94,23 +94,3 @@ Run `prepare` again after a change to anything the module registers for types: i | Option | Default | Description | |---|---|---| | `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | - -## Developing a module - -The starter's `dev:prepare` script runs all three steps that a fresh checkout needs: - -```json [package.json] -{ - "scripts": { - "dev": "npm run dev:prepare && nuxt dev playground", - "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground", - "prepack": "nuxt-module-build build" - } -} -``` - -1. `nuxt-module-build build --stub` points `dist` at your sources. -2. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. -3. `nuxt prepare playground` generates the playground's `.nuxt`. The playground installs the module by its package name, so this step loads the stub from step 1. - -Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date. `build` runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md new file mode 100644 index 00000000..5461279f --- /dev/null +++ b/docs/3.develop-and-publish.md @@ -0,0 +1,67 @@ +--- +title: Develop and Publish +description: Prepare a checkout, work on the module in its playground, and publish it to npm. +--- + +The [module starter](https://github.com/nuxt/starter/tree/module) has a script for each stage of a module's life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each one does. To create a module from the starter, see [Getting Started](/docs/guide/modules/module-builder). + +## Preparing a checkout + +The starter's `dev:prepare` script runs all three steps that a fresh checkout needs: + +```json [package.json] +{ + "scripts": { + "dev": "npm run dev:prepare && nuxt dev playground", + "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground", + "prepack": "nuxt-module-build build" + } +} +``` + +1. `nuxt-module-build build --stub` points `dist` at your sources. See [`build --stub`](/docs/guide/modules/module-builder/commands#build-stub). +2. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +3. `nuxt prepare playground` generates the playground's `.nuxt`. The playground installs the module by its package name, so this step loads the stub from step 1. + +Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date. `build` runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. + +## Working in the playground + +The [playground](/docs/guide/modules/module-builder/project-structure#playground) is a Nuxt app that installs your module, so you can try it out as you change it: + +- `npm run dev` prepares the checkout and starts the playground's development server. It reloads as you change files in `src/`. +- `npm run dev:build` builds the playground with `nuxt build playground`. +- Any other `nuxt` command works against the playground too, as `nuxt playground`. + +The playground loads the module from `dist`. After a stub build, `dist` re-exports your sources. To try the output you publish instead, run `nuxt-module-build build` and start the playground again. Run `dev:prepare` to go back to the stub. + +The starter also has `lint`, `test`, and `test:types` scripts. See [Testing](/docs/guide/modules/testing) in the Module Author Guide for the tests themselves. + +## Publishing + +The `prepack` script runs `nuxt-module-build build`, so the package manager builds the module whenever it packs or publishes it. You don't need to build it yourself first. + +Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, run [publint](https://publint.dev) in the module root. Then pack the module and run [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: + +```bash +npx publint +npm pack +npx @arethetypeswrong/cli ./my-module-1.0.0.tgz +``` + +The starter's `release` script publishes a new version: + +```json [package.json] +{ + "scripts": { + "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags" + } +} +``` + +1. It runs the linter, the tests, and the build. The release stops if any of them fails. +2. `changelogen --release` bumps the version, updates `CHANGELOG.md` from your commit messages, and commits and tags the result. +3. `npm publish` publishes the package. `prepack` builds the module again, so `dist` has the new version. +4. `git push --follow-tags` pushes the release commit and its tag. + +Commit your changes before you run `release`. `changelogen` reads [Conventional Commits](https://www.conventionalcommits.org) to choose the version bump and to write the changelog. diff --git a/docs/3.configuration.md b/docs/4.configuration.md similarity index 100% rename from docs/3.configuration.md rename to docs/4.configuration.md diff --git a/docs/4.typescript.md b/docs/5.typescript.md similarity index 100% rename from docs/4.typescript.md rename to docs/5.typescript.md diff --git a/docs/5.output.md b/docs/6.output.md similarity index 100% rename from docs/5.output.md rename to docs/6.output.md diff --git a/docs/6.exports.md b/docs/7.exports.md similarity index 100% rename from docs/6.exports.md rename to docs/7.exports.md diff --git a/docs/7.transpile-dir.md b/docs/8.transpile-dir.md similarity index 100% rename from docs/7.transpile-dir.md rename to docs/8.transpile-dir.md diff --git a/docs/index.md b/docs/index.md index 08dd7c2f..c1902490 100644 --- a/docs/index.md +++ b/docs/index.md @@ -51,7 +51,7 @@ npm install npm run dev:prepare ``` -`dev:prepare` stubs the module's `dist` directory and generates the `.nuxt` directories that type the module and its playground. See [Commands](/docs/guide/modules/module-builder/commands) for what each step does. +`dev:prepare` stubs the module's `dist` directory and generates the `.nuxt` directories that type the module and its playground. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish) for what each step does. ## Manual installation @@ -78,6 +78,7 @@ Your module also needs the `exports` and `files` fields described in [Project st - [Project structure](/docs/guide/modules/module-builder/project-structure): the files the builder reads. - [Commands](/docs/guide/modules/module-builder/commands): `build`, `build --stub`, and `prepare`. +- [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish): the playground, and releasing to npm. - [Configuration](/docs/guide/modules/module-builder/configuration): extra entries and directories. - [TypeScript](/docs/guide/modules/module-builder/typescript): the module's `tsconfig.json` and its declarations. - [Build output](/docs/guide/modules/module-builder/output): what ends up in `dist`. From 2493e8d74301ba205e5588894b78a30182a1a0f6 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 14:13:57 +0000 Subject: [PATCH 09/28] docs: separate the app's type contexts from the module's own type check --- docs/1.project-structure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 4ec0d8e8..e7506f9f 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -75,7 +75,7 @@ Paths into the runtime directory, such as the one passed to `addPlugin` above, a Code that the module adds to the app: components, composables, plugins, server routes, stylesheets, and any other files. The module registers them from `setup()`, with utilities such as `addPlugin`, `addComponent`, or `addServerHandler`. -Put code for the app in `src/runtime/app/`, and code for the server in `src/runtime/server/`. Nuxt type-checks everything under `runtime/` in the app context except `runtime/server/`, which it type-checks in the server context. See [Augment Types](/docs/guide/modules/recipes-advanced#augment-types) in the Module Author Guide. +Put code for the app in `src/runtime/app/`, and code for the server in `src/runtime/server/`. In an app that installs the module, Nuxt type-checks `runtime/server/` in the server context and the rest of `runtime/` in the app context. The module's own `tsconfig.json` type-checks all of `src/runtime/` with one configuration. See [Augment Types](/docs/guide/modules/recipes-advanced#augment-types) in the Module Author Guide. Each file is transpiled on its own into `dist/runtime/`, keeping its name and its imports. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. From 83cd754106fca56de2454865e7c407c0fe9039ab Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 14:14:07 +0000 Subject: [PATCH 10/28] docs: start the playground without `dev:prepare` to try the build --- docs/3.develop-and-publish.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index 5461279f..0bb204bb 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -33,7 +33,13 @@ The [playground](/docs/guide/modules/module-builder/project-structure#playground - `npm run dev:build` builds the playground with `nuxt build playground`. - Any other `nuxt` command works against the playground too, as `nuxt playground`. -The playground loads the module from `dist`. After a stub build, `dist` re-exports your sources. To try the output you publish instead, run `nuxt-module-build build` and start the playground again. Run `dev:prepare` to go back to the stub. +The playground loads the module from `dist`. After a stub build, `dist` re-exports your sources. To try the output you publish instead, build the module and start the playground directly: + +```bash +npx nuxt-module-build build && npx nuxt dev playground +``` + +`npm run dev` runs `dev:prepare` first, which replaces the build with the stub again. Run `dev:prepare` when you want to go back to the stub. The starter also has `lint`, `test`, and `test:types` scripts. See [Testing](/docs/guide/modules/testing) in the Module Author Guide for the tests themselves. From 1d07727e38f39661d478525ad872ed8928bd2fce Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 14:29:03 +0000 Subject: [PATCH 11/28] docs: note that the docs describe Nuxt 4 and later --- docs/index.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/index.md b/docs/index.md index c1902490..3c45d33e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -19,6 +19,10 @@ To build a module, you need: To use a module built with it, an app needs Nuxt 3 or later. The module entry is compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. +::note +Nuxt 3 has reached end of life, so these docs describe Nuxt 4 and later. Where Nuxt 3 behaves differently, such as type-checking all of a module's runtime files in a single context, they don't cover it. +:: + ## Quick start Create a module from the starter: From a123f3aef8839c47a3a37cc4e3830c52d778164f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 15:03:50 +0000 Subject: [PATCH 12/28] docs: use a non-secret option in the public runtime config example --- docs/1.project-structure.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index e7506f9f..1bdccd37 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -35,6 +35,7 @@ The builder also reads these type exports, and adds them to the types of the app import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' export interface ModuleOptions { + greeting: string apiKey: string } @@ -46,22 +47,28 @@ export interface ModuleRuntimeHooks { 'my-module:ready': () => void } -export interface ModulePublicRuntimeConfig { +export interface ModuleRuntimeConfig { myModule: { apiKey: string } } +export interface ModulePublicRuntimeConfig { + myModule: { greeting: string } +} + export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule', }, defaults: { + greeting: 'Hello', apiKey: '', }, setup(options, nuxt) { const resolver = createResolver(import.meta.url) - nuxt.options.runtimeConfig.public.myModule = { apiKey: options.apiKey } + nuxt.options.runtimeConfig.myModule = { apiKey: options.apiKey } + nuxt.options.runtimeConfig.public.myModule = { greeting: options.greeting } addPlugin(resolver.resolve('./runtime/app/plugins/greeting')) }, }) @@ -85,7 +92,7 @@ Files in the runtime directory can't rely on auto-imports, since Nuxt doesn't ap import { useRuntimeConfig } from '#imports' export function useGreeting() { - return `Hello from ${useRuntimeConfig().public.myModule.apiKey}` + return `${useRuntimeConfig().public.myModule.greeting} from my-module` } ``` From 03fe05dfbfc56836b7bffa5b9378e1fba836e2c5 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 15:04:18 +0000 Subject: [PATCH 13/28] docs: run publint on the packed tarball --- docs/3.develop-and-publish.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index 0bb204bb..5515236a 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -47,11 +47,11 @@ The starter also has `lint`, `test`, and `test:types` scripts. See [Testing](/do The `prepack` script runs `nuxt-module-build build`, so the package manager builds the module whenever it packs or publishes it. You don't need to build it yourself first. -Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, run [publint](https://publint.dev) in the module root. Then pack the module and run [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: +Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, pack the module. `npm pack` runs `prepack`, so the tarball has the built output rather than a stub. Then run [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: ```bash -npx publint npm pack +npx publint ./my-module-1.0.0.tgz npx @arethetypeswrong/cli ./my-module-1.0.0.tgz ``` From 6920021edfb5b20af6fd2e72068c22eade016cbd Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 15:51:13 +0000 Subject: [PATCH 14/28] docs: set runtime config with `updateRuntimeConfig` in the module example --- docs/1.project-structure.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index 1bdccd37..c8abeaf9 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -32,7 +32,7 @@ The builder also reads these type exports, and adds them to the types of the app | `ModulePublicRuntimeConfig` | `PublicRuntimeConfig` from `@nuxt/schema` | Public runtime config keys the module adds. | ```ts [src/module.ts] -import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' +import { addPlugin, createResolver, defineNuxtModule, updateRuntimeConfig } from '@nuxt/kit' export interface ModuleOptions { greeting: string @@ -64,11 +64,13 @@ export default defineNuxtModule({ greeting: 'Hello', apiKey: '', }, - setup(options, nuxt) { + setup(options) { const resolver = createResolver(import.meta.url) - nuxt.options.runtimeConfig.myModule = { apiKey: options.apiKey } - nuxt.options.runtimeConfig.public.myModule = { greeting: options.greeting } + updateRuntimeConfig({ + myModule: { apiKey: options.apiKey }, + public: { myModule: { greeting: options.greeting } }, + }) addPlugin(resolver.resolve('./runtime/app/plugins/greeting')) }, }) From e9e1a6ad3b394812e12a1d9f77bbb77ca7f199b7 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Fri, 13 Nov 2026 16:34:21 +0000 Subject: [PATCH 15/28] docs: describe the root export's value and type exports --- docs/6.output.md | 2 +- docs/7.exports.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/6.output.md b/docs/6.output.md index 3ba17963..10d4bc3c 100644 --- a/docs/6.output.md +++ b/docs/6.output.md @@ -42,7 +42,7 @@ The module's meta. It contains the `meta` of the module definition, and the vers ## `types.d.mts` -The types of the package's root export. It re-exports the default export of `module.d.mts`, and its other exports as types only. It also adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: +The types of the package's root export. It re-exports the value exports of `module.d.mts`, including its default export, and re-exports its type-only exports as types. It also adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: ```ts [dist/types.d.mts] import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' diff --git a/docs/7.exports.md b/docs/7.exports.md index e4c6821e..6ebbe7b5 100644 --- a/docs/7.exports.md +++ b/docs/7.exports.md @@ -3,7 +3,7 @@ title: Exports description: Publish more entry points than the module itself, such as utilities, composables, and components. --- -The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. Anything else you want users to import by name needs its own subpath in the `exports` of `package.json`. +The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. Named values and types exported by `src/module.ts` are re-exported from the root too. Anything else you want users to import by name needs its own subpath in the `exports` of `package.json`. ## Bundled entries From a532eea849449964d568c522ba6fcea4d569adc3 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:51:27 +0000 Subject: [PATCH 16/28] docs: describe building with `tsdown` and remove `--stub` from the commands --- docs/2.commands.md | 82 ++++++++++++++++++---------------- docs/cli/build-module/index.md | 11 +++-- 2 files changed, 48 insertions(+), 45 deletions(-) diff --git a/docs/2.commands.md b/docs/2.commands.md index b7963a2e..444824d0 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -1,6 +1,6 @@ --- title: Commands -description: The `nuxt-module-build` commands and their options. +description: Build a module with `tsdown`, and the `nuxt-module-build` commands and their options. links: - label: Source icon: i-simple-icons-github @@ -8,26 +8,50 @@ links: size: xs --- -`@nuxt/module-builder` installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. +A module builds with `tsdown`, through the [`builder()` plugin](/docs/guide/modules/module-builder/configuration) in its `tsdown.config.ts`. `@nuxt/module-builder` also installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. -The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. To see how the starter's scripts combine them, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). +The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. To see how a module's scripts combine them, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). + +## `tsdown` + +```bash [Terminal] +npx tsdown [--outDir=] [--sourcemap] [--watch] +``` + +Builds the module for publishing with its `tsdown.config.ts`. This is the command that the `prepack` script runs: + +```json [package.json] +{ + "scripts": { + "prepack": "tsdown" + } +} +``` + +`tsdown` needs a `tsdown.config.ts` that uses `builder()`. Without one, it doesn't build the module. The build runs the steps described in [`build`](#build), and tsdown's own options, such as `--outDir` and `--sourcemap`, take precedence over the config. + +`tsdown --watch` builds the module, then rebuilds it when a source file changes, including the files that `src/module.ts` imports and files added to the runtime directory. It leaves the output directory in place while its first build runs. A rebuild only writes the files whose content changed, and removes the files that the build no longer emits. See [Developing against `dist`](/docs/guide/modules/module-builder/develop-and-publish#developing-against-dist). ## `build` ```bash [Terminal] -npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] [--stub] +npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] ``` -Builds the module for publishing. This is the command that the `prepack` script runs: +Builds the module for publishing, with the same output, checks, and warnings as `tsdown`. With a `tsdown.config.ts`, it builds with that config. Without one, it builds `src/module.ts` and `src/runtime/`, plus the entries in the [`build` field of `package.json`](/docs/guide/modules/module-builder/configuration#without-a-tsdown-config), so a module needs no configuration file. -1. If `.nuxt/tsconfig.json` is missing from the module root, it runs [`prepare`](#prepare) first. -2. It reads the [build configuration](/docs/guide/modules/module-builder/configuration) and checks that every relative import in the module code carries its extension. -3. It empties the output directory. -4. It bundles `src/module.ts`, and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries), with tsdown. -5. It transpiles `src/runtime/`, and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries), file by file. -6. It generates the declarations of every entry and runtime file, using the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). -7. It loads the built module to write `dist/module.json`, and writes `dist/types.d.mts`. -8. It checks the paths in `package.json` against the files it produced. +Both commands run these steps: + +1. It checks the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. When it runs as the `prepack` or `prepublishOnly` script, it also checks that the package manager that packs applies `publishConfig`. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). +2. If `.nuxt/tsconfig.json` is missing from the module root, it runs [`prepare`](#prepare) first. +3. It reads the [build configuration](/docs/guide/modules/module-builder/configuration) and checks that the module code loads with Node. See [Module code](/docs/guide/modules/module-builder/typescript#module-code). +4. It empties the output directory. +5. It bundles `src/module.ts`, and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries), with tsdown. +6. It transpiles `src/runtime/`, and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries), file by file. +7. It generates the declarations of every entry and runtime file, using the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). +8. It prints the [size of the output](/docs/guide/modules/module-builder/output#size-report). +9. It loads the built module to write `dist/module.json`, and writes `dist/types.d.mts`. +10. It checks the paths in `package.json` against the files it produced. The build fails when a declaration can't be generated correctly. Other type errors are reported as warnings. See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) for both. @@ -44,30 +68,8 @@ See [Build output](/docs/guide/modules/module-builder/output) for the files the | Option | Default | Description | |---|---|---| | `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | -| `--outDir=` | `dist` | The output directory, relative to the module root. It's emptied before every build, so it must be inside the module. | -| `--sourcemap` | `false` | Emit a source map next to every script. | -| `--stub` | `false` | Write a [stub build](#build-stub) instead. | - -## `build --stub` - -```bash [Terminal] -npx nuxt-module-build build --stub [ROOTDIR] [--cwd=] [--outDir=] -``` - -Writes `dist` as a set of re-exports of your sources, so that anything which loads the module by its package name runs `src/` directly. Use it while you develop the module, with a playground, an app in the same monorepo, or tests that install the module by name. Changes to `src/` don't need another build. - -A stub build writes: - -- `dist/module.mjs`, which re-exports `src/module.ts`. -- `dist/module.d.mts`, which re-exports the types of `src/module.ts`. -- The same pair of files for every other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries). -- `dist/module.json` and `dist/types.d.mts`, as the full build does. - -It doesn't transpile the runtime directory or generate declarations. `src/module.ts` resolves runtime paths relative to itself, so `src/runtime/` is used as it is. A [subpath export](/docs/guide/modules/module-builder/exports) that points into `dist/runtime` resolves after a full build. - -Whatever imports the stub loads the TypeScript sources with its own loader, such as the playground's Nuxt. The builder itself loads `src/module.ts` to write `module.json`, with Node's type stripping. Syntax that Node can't strip (`enum`, `namespace`, parameter properties, JSX, and decorators, among others) is transpiled with oxc, which comes with `tsdown`. Without `tsdown`, the stub build fails and lists each use of such syntax. See [Stub builds](/docs/guide/modules/module-builder/upgrade-v2#stub-builds) in the upgrade guide. - -Options that a full build rejects in a [deprecated build config](/docs/guide/modules/module-builder/configuration#buildconfigts) are listed as a warning instead, and the stub build continues. +| `--outDir=` | | The output directory, relative to the module root. Takes precedence over `outDir` in the tsdown config, which defaults to `dist`. It's emptied before every build, so it must be inside the module. | +| `--sourcemap` | | Emit a source map next to every script. Takes precedence over `sourcemap` in the tsdown config. | ## `prepare` @@ -77,9 +79,11 @@ npx nuxt-module-build prepare [ROOTDIR] [--cwd=] Generates `.nuxt` in the module root. It runs `nuxt prepare` on the module root, as a Nuxt app with your module as its only module and auto-imports disabled. It writes nothing to `dist`. -Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` it generates. That gives your editor, your type check, and the declarations that `build` generates the same types: `@nuxt/schema`, the `#app`, `#imports`, and `#build` aliases, and anything your module adds, such as its templates and server routes. See [TypeScript](/docs/guide/modules/module-builder/typescript). +Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` it generates. That gives your editor, your type check, and the declarations that the build generates the same types: `@nuxt/schema`, the `#app`, `#imports`, and `#build` aliases, and anything your module adds, such as its templates and server routes. See [TypeScript](/docs/guide/modules/module-builder/typescript). + +It also writes `.nuxt/module-builder/types.d.mts`, which re-exports `src/module.ts` and adds the same [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) as `dist/types.d.mts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it. -`prepare` loads `src/module.ts` in the same way as the stub build, so relative imports in module code need their extensions here too. Until they're in place, `prepare` lists the imports to fix and doesn't generate `.nuxt`. +`prepare` loads `src/module.ts` with Node, and reads the options of `builder()` from `tsdown.config.ts`, which it loads with Node too. Module code therefore follows the rules in [Module code](/docs/guide/modules/module-builder/typescript#module-code). Until it does, `prepare` lists each problem and doesn't generate `.nuxt`. `prepare` fails when the tsdown config sets `cwd` to another directory. tsdown's hooks and plugins don't run for `prepare`. Run `prepare` again after a change to anything the module registers for types: its options, templates, type declarations, or server routes. diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md index c51025a3..91fe3372 100644 --- a/docs/cli/build-module/index.md +++ b/docs/cli/build-module/index.md @@ -9,7 +9,7 @@ links: --- ```bash [Terminal] -npx nuxt build-module build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] [--stub] +npx nuxt build-module build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] npx nuxt build-module prepare [ROOTDIR] [--cwd=] ``` @@ -17,7 +17,7 @@ The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/modu ## `build` -Builds the module into `dist` for publishing. With `--stub`, it writes `dist` as re-exports of your sources instead, for development. See [`build`](/docs/guide/modules/module-builder/commands#build) and [`build --stub`](/docs/guide/modules/module-builder/commands#build-stub). +Builds the module into `dist` for publishing, with the module's `tsdown.config.ts` when it has one. It produces the same output as `tsdown`. See [`build`](/docs/guide/modules/module-builder/commands#build). ### Arguments @@ -30,13 +30,12 @@ Builds the module into `dist` for publishing. With `--stub`, it writes `dist` as | Option | Default | Description | |---|---|---| | `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | -| `--outDir=` | `dist` | The output directory, relative to the module root. It's emptied before every build, so it must be inside the module. | -| `--sourcemap` | `false` | Emit a source map next to every script. | -| `--stub` | `false` | Write a stub build instead. | +| `--outDir=` | | The output directory, relative to the module root. Takes precedence over `outDir` in the tsdown config, which defaults to `dist`. It's emptied before every build, so it must be inside the module. | +| `--sourcemap` | | Emit a source map next to every script. Takes precedence over `sourcemap` in the tsdown config. | ## `prepare` -Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends, and the declarations that the root export's `types` condition points at while `package.json` points at the module's sources. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). ### Arguments From 2f0708ccf25705b20cedfb754eb38a7c6eecbcef Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:52:26 +0000 Subject: [PATCH 17/28] docs: describe source exports, developing against `dist` and the publish checks --- docs/3.develop-and-publish.md | 146 +++++++++++++++++++++++++++++----- 1 file changed, 124 insertions(+), 22 deletions(-) diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index 5515236a..c768f192 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -3,71 +3,173 @@ title: Develop and Publish description: Prepare a checkout, work on the module in its playground, and publish it to npm. --- -The [module starter](https://github.com/nuxt/starter/tree/module) has a script for each stage of a module's life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each one does. To create a module from the starter, see [Getting Started](/docs/guide/modules/module-builder). +A module has a script for each stage of its life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each one does. To create a module from the starter, see [Getting Started](/docs/guide/modules/module-builder). To move a module that used stub builds, see [Stub builds](/docs/guide/modules/module-builder/upgrade-v2#stub-builds) in the upgrade guide. ## Preparing a checkout -The starter's `dev:prepare` script runs all three steps that a fresh checkout needs: +The [playground](/docs/guide/modules/module-builder/project-structure#playground) installs the module by its package name, so it loads whatever `package.json` points at. Which setup to use depends on the package manager that publishes the module: + +- With pnpm or Yarn 4, `package.json` points at your sources, and `publishConfig` holds the `dist` paths that are published. The playground runs your sources, and `dist` is only written when you build. See [Source exports](#source-exports). +- With npm, Yarn 3 or earlier, or bun, `package.json` points at `dist`, and `tsdown --watch` rebuilds it while you develop. See [Developing against `dist`](#developing-against-dist). + +Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date, such as after the module registers a new template or server route. The build runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. + +### Source exports + +pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level ones. With either of them, point `exports` and `main` at `src`, and the same fields in `publishConfig` at `dist`: ```json [package.json] { + "exports": { + ".": { + "types": "./.nuxt/module-builder/types.d.mts", + "import": "./src/module.ts" + } + }, + "main": "./src/module.ts", + "files": [ + "dist" + ], + "publishConfig": { + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + } + }, + "main": "./dist/module.mjs" + }, "scripts": { - "dev": "npm run dev:prepare && nuxt dev playground", - "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground", - "prepack": "nuxt-module-build build" + "dev": "nuxt dev playground", + "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground", + "prepack": "tsdown" + } +} +``` + +1. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`, and the `.nuxt/module-builder/types.d.mts` that the root export's `types` condition points at. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +2. `nuxt prepare playground` generates the playground's `.nuxt`. It loads `src/module.ts` through `exports`. + +`publishConfig` replaces each field as a whole, so `publishConfig.exports` repeats every subpath and condition of `exports`. See [Exports](/docs/guide/modules/module-builder/exports#source-exports) for subpaths. + +The playground has to resolve the module's name to the module directory itself. With pnpm, install it with `workspace:*` and list `playground` in `pnpm-workspace.yaml`, or with `link:..`: + +```yaml [pnpm-workspace.yaml] +packages: + - playground +``` + +```json [playground/package.json] +{ + "dependencies": { + "my-module": "workspace:*" } } ``` -1. `nuxt-module-build build --stub` points `dist` at your sources. See [`build --stub`](/docs/guide/modules/module-builder/commands#build-stub). -2. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). -3. `nuxt prepare playground` generates the playground's `.nuxt`. The playground installs the module by its package name, so this step loads the stub from step 1. +The playground's type check includes your sources and the files they import types from. See [The playground's `tsconfig.json`](/docs/guide/modules/module-builder/typescript#with-source-exports) for the errors this can report. + +There is no `dist` while you develop, so code that reaches into `dist` by path points at `src` instead. Resolve runtime files relative to `src/module.ts` and without an extension, as in `createResolver(import.meta.url).resolve('./runtime/app/plugins/greeting')`. The build keeps the layout of `src` in `dist`, and Nuxt adds the extension. -Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date. `build` runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. +Yarn 4 packs `typesVersions` as written. Keep `typesVersions` at the top level, pointing at `dist`: TypeScript only reads it under `node10` module resolution, which a playground doesn't use. + +### Developing against `dist` + +npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point `package.json` at `dist`, and build it before the playground is prepared: + +```json [package.json] +{ + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + } + }, + "main": "./dist/module.mjs", + "files": [ + "dist" + ], + "scripts": { + "dev": "nuxt dev playground", + "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare playground", + "prepack": "tsdown" + } +} +``` + +1. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. +2. `tsdown` builds `dist`. See [`tsdown`](/docs/guide/modules/module-builder/commands#tsdown). +3. `nuxt prepare playground` generates the playground's `.nuxt`. It loads `dist/module.mjs` through `exports`. + +With npm, install the module in the playground with `"my-module": "file:.."` and list `playground` in the root `workspaces`, so npm links the module into the playground. With Yarn 1, use `"my-module": "link:.."`. + +While the playground runs, run `tsdown --watch` next to it. It leaves `dist` in place while its first build runs, so the two can start together. Each change under `src` rebuilds `dist`, and a rebuild only writes the files whose content changed. ## Working in the playground -The [playground](/docs/guide/modules/module-builder/project-structure#playground) is a Nuxt app that installs your module, so you can try it out as you change it: +The playground is a Nuxt app that installs your module, so you can try it out as you change it: -- `npm run dev` prepares the checkout and starts the playground's development server. It reloads as you change files in `src/`. +- `npm run dev` starts the playground's development server with `nuxt dev playground`. - `npm run dev:build` builds the playground with `nuxt build playground`. - Any other `nuxt` command works against the playground too, as `nuxt playground`. -The playground loads the module from `dist`. After a stub build, `dist` re-exports your sources. To try the output you publish instead, build the module and start the playground directly: +Nuxt serves the files of the runtime directory through Vite, so an edited component updates in place, and an edited plugin reloads the page. With `dist`, this applies once `tsdown --watch` has rebuilt the file. The playground loads the module itself once, when `nuxt dev` starts: restart `nuxt dev` after you change `src/module.ts` or the files it imports. + +With source exports, the playground always runs your sources. With `package.json` pointing at `dist`, it runs the last build. To try the output of a full build there, build the module and start the playground: ```bash -npx nuxt-module-build build && npx nuxt dev playground +npx tsdown && npx nuxt dev playground ``` -`npm run dev` runs `dev:prepare` first, which replaces the build with the stub again. Run `dev:prepare` when you want to go back to the stub. - -The starter also has `lint`, `test`, and `test:types` scripts. See [Testing](/docs/guide/modules/testing) in the Module Author Guide for the tests themselves. +See [Testing](/docs/guide/modules/testing) in the Module Author Guide for the tests themselves. ## Publishing -The `prepack` script runs `nuxt-module-build build`, so the package manager builds the module whenever it packs or publishes it. You don't need to build it yourself first. +The `prepack` script runs `tsdown`, so the package manager builds the module whenever it packs or publishes it. You don't need to build it yourself first. -Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, pack the module. `npm pack` runs `prepack`, so the tarball has the built output rather than a stub. Then run [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: +Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, pack the module with the package manager that publishes it, such as `pnpm pack` for source exports. Then run [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: ```bash -npm pack +pnpm pack npx publint ./my-module-1.0.0.tgz npx @arethetypeswrong/cli ./my-module-1.0.0.tgz ``` -The starter's `release` script publishes a new version: +A `release` script can publish a new version in one step: ```json [package.json] { "scripts": { - "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags" + "release": "pnpm lint && pnpm test && pnpm prepack && changelogen --release && pnpm publish && git push --follow-tags" } } ``` 1. It runs the linter, the tests, and the build. The release stops if any of them fails. 2. `changelogen --release` bumps the version, updates `CHANGELOG.md` from your commit messages, and commits and tags the result. -3. `npm publish` publishes the package. `prepack` builds the module again, so `dist` has the new version. +3. `pnpm publish` publishes the package. `prepack` builds the module again, so `dist` has the new version. 4. `git push --follow-tags` pushes the release commit and its tag. +With source exports, publish with `pnpm publish` or `yarn npm publish`. With `dist`, `npm publish` works too. + Commit your changes before you run `release`. `changelogen` reads [Conventional Commits](https://www.conventionalcommits.org) to choose the version bump and to write the changelog. + +### Checks on published paths + +Every build reads the path fields of `package.json`, such as `exports`, `main`, and `types`, with the fields of `publishConfig` in place of the top-level ones. It fails before building when one of them points at a path that doesn't work once the package is installed: + +- A TypeScript source other than a declaration, which Node doesn't load from `node_modules`. +- A path that the pack leaves out, because `files` doesn't list it. Without `files`, a path into `.nuxt` counts as left out. + +Every pack includes `package.json` and the file that `main` points at, so `files` doesn't have to list them. To publish a file other than a TypeScript source as it is, list it in `files`. + +An entry of `imports` is checked in the same way once the build is done, and only when the build output imports it. An entry that the build bundles into `module.mjs` can keep pointing at `src`. + +When `tsdown` or `nuxt-module-build build` runs as the `prepack` or `prepublishOnly` script, the build also fails when the package manager that packs would publish such a path as written: + +- The package manager has to apply `publishConfig` to each field that points at your sources. pnpm applies it to all of them. Yarn 4 applies it to every field but `typesVersions`, Yarn 3 to `exports`, `imports`, `main`, and `module`, and Yarn 2 to `main` and `module`. npm, Yarn 1, and bun pack `package.json` as written. +- `publishConfig` has to set each of those fields, to paths that pass the checks above. + +The build reads the package manager from the `npm_config_user_agent` and `npm_execpath` environment variables, and the script from `npm_lifecycle_event`. A `prepack` script that runs another script, such as `"prepack": "npm run build"`, isn't checked, because the nested script runs as `build`. Run `tsdown` or `nuxt-module-build build` from `prepack` directly. With source exports, a `release` script that runs `npm publish` fails, even when `pnpm run` starts it. `npm publish` of a tarball that `pnpm pack` wrote works, as its `package.json` already has the `dist` paths and the build doesn't run again. + +After the build, a warning lists the paths in `package.json` that the build didn't produce. From 74c1e7bc1ec189d84d7085314b4dc16de5dd7256 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:53:10 +0000 Subject: [PATCH 18/28] docs: configure the build with `builder()` in `tsdown.config.ts` --- docs/4.configuration.md | 170 +++++++++++++++++++++++++++++----------- 1 file changed, 125 insertions(+), 45 deletions(-) diff --git a/docs/4.configuration.md b/docs/4.configuration.md index e663288e..da591012 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -1,23 +1,47 @@ --- title: Configuration -description: Build entries other than `src/module.ts`, keep packages external, and the deprecated `build.config.ts`. +description: Configure the build with `builder()` in `tsdown.config.ts`, build entries other than `src/module.ts`, and keep packages external. --- -A module with `src/module.ts` and `src/runtime/` needs no configuration. To build other files, list them in the `build.entries` field of `package.json`: +The build is configured in a `tsdown.config.ts` in the module root, with the `builder()` plugin from `@nuxt/module-builder/tsdown`. A module with `src/module.ts` and `src/runtime/` needs no options: -```json [package.json] -{ - "build": { - "entries": [ - "./src/utils", - { "input": "./src/kit/index", "name": "kit" }, - { "input": "src/features/", "outDir": "dist/features", "ext": "js" } - ] - } -} +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [builder()], +}) ``` -An entry is either bundled, like `src/module.ts`, or a directory transpiled file by file, like `src/runtime/`. +`tsdown` builds the module with this config, and so does `nuxt-module-build build`. See [Commands](/docs/guide/modules/module-builder/commands). The config is module code, so its relative imports carry their extension, as described in [Module code](/docs/guide/modules/module-builder/typescript#module-code). + +## `builder()` options + +`builder()` takes three options: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [ + builder({ + entries: [ + './src/utils', + { input: './src/kit/index', name: 'kit' }, + { input: 'src/features/', outDir: 'dist/features', ext: 'js' }, + ], + externals: ['shiki'], + replace: { __VERSION__: JSON.stringify('1.0.0') }, + }), + ], +}) +``` + +- `entries`: files to build besides `src/module.ts`. An entry is either bundled, like `src/module.ts`, or a directory transpiled file by file, like `src/runtime/`. See [Bundled entries](#bundled-entries) and [Directory entries](#directory-entries). +- `externals`: imports that are never bundled. See [Externals](#externals). +- `replace`: compile-time replacements in the bundled entries, as `{ search: replacement }`, or as `{ values, delimiters, preventAssignment, objectGuards }`. ## Bundled entries @@ -30,28 +54,20 @@ A string, or an object with `input` and an optional `name`, is bundled with tsdo Each bundled entry is written to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries). +Relative imports in a bundled entry carry the imported file's extension, as in module code, because [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports) point at the entry as it is. + +## Externals + Bundled entries share the module entry's externals. These are never bundled: - `@nuxt/kit`, `@nuxt/schema`, `nuxt`, `vue`, and the `#app`, `#build`, and `#imports` aliases. -- Your module's own package name, and the `#` subpath imports in the `imports` field of `package.json`. +- Your module's own package name. - `dependencies`, `peerDependencies`, and `optionalDependencies`. -- The packages in `build.externals`. +- The imports in `builder({ externals })`. -Any other package an entry imports, such as a `devDependency`, is bundled into it. +Any other import is bundled into the entry that imports it, such as a `devDependency`, or a `#` subpath import from the `imports` field of `package.json`. -## Externals - -To keep a package that isn't a dependency out of the bundled entries, list it in the `build.externals` field of `package.json`. Each name also covers its subpaths, so `shiki` keeps `shiki/core` external too: - -```json [package.json] -{ - "build": { - "externals": ["shiki"] - } -} -``` - -The import is then kept as written, and resolves in the app that installs the module. +To keep a package that isn't a dependency out of the bundled entries, list it in `externals`. Each name also covers its subpaths, so `shiki` keeps `shiki/core` external too. A regular expression matches the import as written. The import is then kept as written, and resolves in the app that installs the module. tsdown's `deps.neverBundle` adds to the same list. ## Directory entries @@ -65,30 +81,94 @@ An object whose `input` ends in `/` is a directory. Every file in it is transpil The entry above writes the files of `src/features/` to `dist/features/`, with `.js` scripts and `.d.ts` declarations. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. -Files in a directory entry follow the rules of the runtime directory. Their relative imports can leave out the extension, and module code that imports them points at their output instead of bundling them. +Files in a directory entry follow the rules of the runtime directory. Their relative imports can leave out the extension, unless module code imports them by value. Module code that imports them points at their output instead of bundling them. -## `build.config.ts` +## tsdown options -`build.config.ts` (or `.mts`, `.js`, `.mjs`) and the `unbuild` field of `package.json` are deprecated. The build reads them, warns, and still applies these options: +Other tsdown options apply as usual, such as `outDir` (inside the module), `sourcemap`, `define`, `report`, `plugins`, and `hooks`. `--outDir` and `--sourcemap` on the command line take precedence over the config. -- `entries`, in the shapes described above. -- `externals`: package names, as in [`build.externals`](#externals), and regular expressions. -- `replace` and `rollup.replace`: compile-time replacements in the bundled entries. -- `sourcemap`: `true` emits source maps, like `--sourcemap`. -- The `build:before`, `rollup:done`, and `build:done` hooks. +`builder()` sets these options itself, so the build fails when the config sets them too: -`mkdist:*` hooks are ignored with a warning, and a few other options are accepted at their defaults. Any other option fails the build, with a list of each one and the file it comes from. To type the file, import `defineBuildConfig` from `@nuxt/module-builder`: +- `entry`: list entries in `builder({ entries })` instead. +- `format`, other than `esm`. +- `dts`, other than `true`. Declarations are generated with the module's own tsconfig, see [TypeScript](/docs/guide/modules/module-builder/typescript#declarations). +- `clean`: the output directory is emptied before a one-off build, and a watched build removes the files it no longer emits. +- `unbundle`, `exports`, `fixedExtension: false`, `outExtensions`, `platform` other than `node`, and `workspace`. +- `external` and `noExternal`: use `builder({ externals })`, `deps.neverBundle`, or `deps.alwaysBundle` instead. +- `deps.neverBundle` set to `true` or a function: list the imports instead. -```ts [build.config.ts] -import { defineBuildConfig } from '@nuxt/module-builder' +The build also fails when another plugin changes one of these options, or when `outputOptions.entryFileNames` changes the file names of the bundled entries. -export default defineBuildConfig({ +### Hooks + +`builder()` has no hooks of its own, and fails when it's given `hooks`. Use tsdown's `hooks` in the config, which receive tsdown's context. `ctx.options.cwd` is the module root, and `ctx.options.outDir` the output directory: + +- `build:prepare` runs before `builder()` checks the module's imports and empties the output directory, so it can generate sources. Files written into the output directory there are removed. +- `build:done` runs once the build is complete, after `module.json` and `types.d.mts` are written and the paths in `package.json` are checked. + +To add a file to the output, emit it from a plugin. It's written before the paths in `package.json` are checked: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ hooks: { - 'build:done'(ctx) { - console.log(`Built ${ctx.options.name} into ${ctx.options.outDir}`) - }, + 'build:prepare': ctx => generateTypes(ctx.options.cwd), }, + plugins: [ + builder(), + { + name: 'config-cjs', + generateBundle() { + this.emitFile({ type: 'asset', fileName: 'config.cjs', source: 'module.exports = {}\n' }) + }, + }, + ], }) ``` -Move `entries` and string `externals` to the `build` field of `package.json`, and delete the file once nothing else is left in it. See [Build configuration](/docs/guide/modules/module-builder/upgrade-v2#build-configuration) in the upgrade guide for how each option is applied, and for the options that fail the build. +tsdown's hooks and plugins don't run for `nuxt-module-build prepare`, or for a playground that loads the module from its sources. Commit generated sources that `src/module.ts` imports, or generate them in the module's `dev:prepare` script before `nuxt-module-build prepare`. + +### Other builds in the same config + +To build other entries alongside the module, export an array of configs. Give each config its own `outDir`, because the module's output directory is emptied before the build. Call `builder()` once, in the config that builds the module: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig([ + { plugins: [builder()] }, + { entry: { cli: 'src/cli.ts' }, outDir: 'dist-cli' }, +]) +``` + +## Without a tsdown config + +Without a `tsdown.config.ts`, `nuxt-module-build build` builds `src/module.ts` and `src/runtime/` on its own, and reads build options such as `entries` and `externals` from the `build` field of `package.json`: + +```json [package.json] +{ + "build": { + "entries": ["./src/utils"], + "externals": ["shiki"] + } +} +``` + +Entries take the same shapes as in `builder({ entries })`. `tsdown` needs the config to build the module, so a module that builds with `tsdown` moves these options into `builder()`. With a tsdown config, a `build` field fails the build. + +## `build.config.ts` + +`build.config.ts` (or `.mts`, `.js`, `.mjs`) and the `unbuild` field of `package.json` are deprecated. Without a tsdown config, the build reads them, warns, and still applies these options: + +- `entries`, in the shapes described above. +- `externals`: package names and regular expressions. +- `replace` and `rollup.replace`: compile-time replacements in the bundled entries. +- `sourcemap`: `true` emits source maps, like `--sourcemap`. +- The `build:before`, `rollup:done`, and `build:done` hooks. + +`mkdist:*` hooks are ignored with a warning, and a few other options are accepted at their defaults. Any other option fails the build, with a list of each one and the file it comes from. With a tsdown config, `build.config.ts` and the `unbuild` field fail the build. + +Move their options into `builder()` and tsdown's own `hooks`, then delete the file or remove the field. See [Moving from build.config.ts](/docs/guide/modules/module-builder/upgrade-v2#moving-from-buildconfigts) in the upgrade guide for how each option maps. From 6feeb52db034d5d1ed69a3831c04aa14bb0dee61 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:53:45 +0000 Subject: [PATCH 19/28] docs: describe module code that loads with Node and the playground's type check --- docs/5.typescript.md | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/5.typescript.md b/docs/5.typescript.md index 175d16f9..17733b38 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -16,7 +16,7 @@ The module root has a `tsconfig.json` of its own, which extends the `.nuxt/tscon } ``` -This single tsconfig covers `src/module.ts` and `src/runtime/` alike. Your editor, your type check, and the declarations that `nuxt-module-build build` generates all read it, so they see the same types. +This single tsconfig covers `src/module.ts` and `src/runtime/` alike. Your editor, your type check, and the declarations that the build generates all read it, so they see the same types. The `.nuxt` in the module root types the module as Nuxt sees it with the module installed alone, at its default options, with auto-imports disabled. It's separate from the playground's `.nuxt`, which reflects the playground's configuration and any other modules it installs. @@ -44,6 +44,18 @@ To type-check the module and the playground, run the type check once in each: } ``` +### With source exports + +With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the playground resolves the module to your sources. Its type check then includes `src/module.ts`, the runtime files, and the files they import types from, checked with the playground's compiler options. The root export's `types` condition points at `.nuxt/module-builder/types.d.mts`, so the playground sees the module's [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets). + +The errors this can report, and their fixes: + +- `#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context, through types that module code imports from a runtime file that uses them: move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. +- Relative imports without extensions (TS2835, TS2834), in a context that resolves imports like Node: add extensions to type-only relative imports as well. +- Globals that the module declares in its own `.d.ts` not found (TS2304), because the playground doesn't include that file: reference it with `/// ` from the files that use the globals. +- The module's own aliases not found (TS2307): move an alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`. TypeScript resolves those from the module's files in any project. Declare the types of an alias that the module adds itself, such as a virtual module, with `addTypeTemplate(template, { nuxt: true, node: true })`, so both of the playground's contexts include them. +- Other errors in runtime files: fix them, or check the module with the same compiler options. + ## Monorepos In a monorepo, give the module its own `tsconfig.json` as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Move any `compilerOptions` the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check and to its declarations. @@ -52,7 +64,7 @@ The tsconfig that covers your module might extend or reference another app's `.n ## Declarations -`nuxt-module-build build` generates declarations from your module's own files, with the module's tsconfig: +The build generates declarations from your module's own files, with the module's tsconfig: - The module entry and every other bundled entry, with TypeScript, or with oxc when `isolatedDeclarations` is set. - Every script in the runtime directory and other directory entries, with TypeScript. @@ -104,9 +116,22 @@ export default module Without `isolatedDeclarations`, the build prints a reminder once per run outside CI. Both settings work. -## Recommended compiler options +## Module code + +`nuxt-module-build prepare` and the build load the module's build-time code with Node, as it is. Module code is `src/module.ts`, every file it imports by value (runtime files included), and `tsdown.config.ts`. Node strips types and resolves imports as written, so module code follows these rules: + +- Relative imports carry the imported file's extension: `./utils.ts`, not `./utils`, `./utils.js`, or `./dir`. +- TypeScript syntax that stripping types doesn't remove isn't used: `enum`, `namespace` with values, parameter properties, `value` assertions, `import x = require()`, `export =`, and decorators. +- Imports don't go through tsconfig `paths` aliases. Use a relative import, or an entry in the `imports` of `package.json`, which Node resolves itself and the build bundles. +- Values aren't imported from `.vue`, `.tsx`, or `.jsx` files. Move a value the module needs into a `.ts` file. +- JSON is imported with an import attribute, as `import pkg from '../package.json' with { type: 'json' }`. Read properties from it rather than destructuring it, so `module.mjs` only contains the properties that are read. +- Values aren't imported from `#app`, `#imports`, or `#build/*`, which only exist inside a Nuxt app. Move the code that needs them into a runtime file the module adds, such as a plugin. + +`prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and piece of syntax that breaks these rules, each with its file, line, column, and fix. Until the list is empty, `prepare` doesn't generate `.nuxt`. + +Type-only imports don't stop the module from loading, as Node never loads them. Write their extensions too: a type check that resolves imports like Node requires them. Relative imports in other [bundled entries](/docs/guide/modules/module-builder/configuration#bundled-entries) carry their extension as well. Runtime files that module code doesn't import by value keep extensionless imports, as the build adds the extension to their output. -`erasableSyntaxOnly` makes the type check report syntax that Node's type stripping can't run, such as `enum` and parameter properties. The stub build and `prepare` load such syntax only when `tsdown` is installed: +`erasableSyntaxOnly` makes the type check report the syntax that Node's type stripping can't run: ```json [tsconfig.json] { @@ -118,4 +143,4 @@ Without `isolatedDeclarations`, the build prints a reminder once per run outside } ``` -The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension in module code type-check without further settings. +The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension type-check without further settings. From 5d668f1ae58dcb51ba8ac2a9499359eed3211cdf Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:54:22 +0000 Subject: [PATCH 20/28] docs: describe the size report and the source types that `prepare` writes --- docs/6.output.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/docs/6.output.md b/docs/6.output.md index 10d4bc3c..8c787bd2 100644 --- a/docs/6.output.md +++ b/docs/6.output.md @@ -1,6 +1,6 @@ --- title: Build Output -description: The files that `nuxt-module-build build` writes to `dist`. +description: The files that the build writes to `dist`, and the size report it prints. --- A module with `src/module.ts`, `src/runtime/`, and a `./src/utils` [entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into: @@ -16,7 +16,7 @@ dist/ โ””โ”€โ”€ runtime/ # src/runtime/, file by file ``` -The output is ES modules only. Pass `--sourcemap` to emit a source map next to every script. +The output is ES modules only. Set `sourcemap` in `tsdown.config.ts`, or pass `--sourcemap`, to emit a source map next to every script. ## `module.mjs` @@ -62,6 +62,8 @@ export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, t When `src/module.ts` doesn't export `ModuleOptions`, `types.d.mts` infers it from the default export. +[`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes the same augmentations for your sources to `.nuxt/module-builder/types.d.mts`, which re-exports `src/module.ts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it while you develop. + ## Runtime files Every file under `src/runtime/` is emitted under `dist/runtime/` with its name intact, apart from the extension: @@ -109,3 +111,24 @@ Declarations of runtime files are rewritten so they resolve in the app that inst - Other Nuxt aliases, such as `#build/*` and `#imports`, are kept. They resolve against the `.nuxt` of the app that installs the module. See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) for how declarations are generated, and the errors that fail the build. + +## Size report + +Every build prints the size of its output with tsdown's `report`. When `src/runtime/` or another [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries) exists, the report is a summary, followed by one line for each bundled entry and transpiled directory, with the size of its code and of its declarations: + +```bash [Terminal] +โ„น 22 files, total: 5.11 kB +โ„น dist/utils.mjs 74 B ยท types 47 B +โ„น dist/module.mjs 436 B ยท types 589 B +โ„น dist/runtime/ 1.18 kB ยท types 2.78 kB ยท 18 files +``` + +Otherwise, it has a line for each file. `module.json` and `types.d.mts` are written after the report, so they aren't in it. Under `tsdown --watch`, the summary of a rebuild only counts the files it wrote, while the lines for each entry and directory cover the whole build. + +Set `report` in `tsdown.config.ts` to change it: `{ summary: true }` or `{ summary: false }`, `{ gzip: false }` to skip compressing each file, `{ brotli: true }`, or `false` to turn it off. The lines for each entry and directory follow a summary only. + +To check the published size in CI of a module whose `package.json` points at `dist`, `npm pack --dry-run --json` lists what gets published: each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`: + +```bash [Terminal] +npm pack --dry-run --json | jq '.[0] | { size, unpackedSize, files: [.files[] | { path, size }] }' +``` From cf862f9e26770398eec6de4548daaf7e0ff0147f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:54:43 +0000 Subject: [PATCH 21/28] docs: describe subpath exports with source exports --- docs/7.exports.md | 50 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/docs/7.exports.md b/docs/7.exports.md index 6ebbe7b5..b98ebbf0 100644 --- a/docs/7.exports.md +++ b/docs/7.exports.md @@ -5,9 +5,11 @@ description: Publish more entry points than the module itself, such as utilities The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. Named values and types exported by `src/module.ts` are re-exported from the root too. Anything else you want users to import by name needs its own subpath in the `exports` of `package.json`. +The examples on this page show the published `exports`, which point at `dist`. With source exports, put them in `publishConfig.exports`, and point each subpath of `exports` at its source. See [Source exports](#source-exports). + ## Bundled entries -A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into `dist/.mjs` and `dist/.d.mts`. Export it with both: +A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries), such as `./src/utils` in `builder({ entries })`, builds into `dist/.mjs` and `dist/.d.mts`. Export it with both: ```json [package.json] { @@ -20,9 +22,6 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri "types": "./dist/utils.d.mts", "import": "./dist/utils.mjs" } - }, - "build": { - "entries": ["./src/utils"] } } ``` @@ -92,9 +91,48 @@ export default defineNuxtModule({ `` and `` are then available without an import. Composables and utilities work the same way: export them from an index, and register them with `addImports` or `addImportsDir`. ::note -A [stub build](/docs/guide/modules/module-builder/commands#build-stub) doesn't write `dist/runtime/`. These subpaths resolve once the module has been built with `nuxt-module-build build`. +With `exports` that point at `dist`, these subpaths resolve once the module has been built. [Source exports](#source-exports) resolve them to your sources while you develop. :: +## Source exports + +With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), `exports` point at your sources, and `publishConfig.exports` holds the paths in `dist`. The playground, and anything else that installs the module from the workspace, then loads every export from `src/` without a build: + +```json [package.json] +{ + "exports": { + ".": { + "types": "./.nuxt/module-builder/types.d.mts", + "import": "./src/module.ts" + }, + "./utils": "./src/utils.ts", + "./components": "./src/runtime/app/components/index.ts" + }, + "publishConfig": { + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + }, + "./utils": { + "types": "./dist/utils.d.mts", + "import": "./dist/utils.mjs" + }, + "./components": { + "types": "./dist/runtime/app/components/index.d.ts", + "import": "./dist/runtime/app/components/index.js" + } + } + } +} +``` + +- Each subpath of `exports` points at the source file that the build turns into the matching path of `publishConfig.exports`. `publishConfig.exports` replaces `exports` as a whole, so it repeats every subpath. +- The root export's `types` condition points at the declarations that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes, so the [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` apply in the playground. A subpath has no augmentations, so it points at its source alone. +- A subpath that code outside Nuxt imports, such as a plugin for a plain Vite app, can keep pointing at `dist` in `exports`, so that code loads the built file. Build the module before using it. + +The build checks the paths in `publishConfig.exports`, not the source paths in `exports`. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). + ## Importing your own exports -Runtime code and module code can import the module's own package name, such as `my-module/utils`. These imports are never bundled, and resolve to the published files in the app that installs the module. While the build generates declarations, they resolve to your sources instead, so they type-check before `dist` exists. +Runtime code and module code can import the module's own package name, such as `my-module/utils`. These imports are never bundled, and resolve to the published files in the app that installs the module. While the build generates declarations, they resolve to your sources instead, so they type-check before `dist` exists. With source exports, the subpaths and their `dist` paths are read from `publishConfig.exports`. From c00efbed6638ff222c87346ee73c59b1d0f37b15 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:55:11 +0000 Subject: [PATCH 22/28] docs: show source exports and `tsdown.config.ts` in the project structure --- docs/1.project-structure.md | 64 ++++++++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index c8abeaf9..ec75d301 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -14,7 +14,8 @@ my-module/ โ”‚ โ””โ”€โ”€ server/ # server routes, middleware, and Nitro plugins โ”œโ”€โ”€ playground/ # a Nuxt app that installs the module โ”œโ”€โ”€ package.json -โ””โ”€โ”€ tsconfig.json +โ”œโ”€โ”€ tsconfig.json +โ””โ”€โ”€ tsdown.config.ts # the build configuration ``` ## `src/module.ts` @@ -76,9 +77,9 @@ export default defineNuxtModule({ }) ``` -Relative imports in `src/module.ts`, and in every file it imports outside the runtime directories, carry the imported file's extension: `./utils.ts`, not `./utils`. The [stub build](/docs/guide/modules/module-builder/commands#build-stub) and [`prepare`](/docs/guide/modules/module-builder/commands#prepare) load these files with Node, which resolves relative specifiers as written. Type-only imports are exempt. +[`prepare`](/docs/guide/modules/module-builder/commands#prepare) and the build load `src/module.ts`, and every file it imports by value, with Node. Relative imports in these files carry the imported file's extension, `./utils.ts` rather than `./utils`, and the files use only syntax that Node's type stripping removes. See [Module code](/docs/guide/modules/module-builder/typescript#module-code) for all the rules. -Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/app/plugins/greeting.ts` is emitted as `dist/runtime/app/plugins/greeting.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source in development, and the `.js` output once the module is published. +Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/app/plugins/greeting.ts` is emitted as `dist/runtime/app/plugins/greeting.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source when `package.json` points at your sources, and the `.js` output from `dist`. ## `src/runtime/` @@ -100,20 +101,22 @@ export function useGreeting() { The `.nuxt` that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) generates for your module disables auto-imports too. A missing import is then a type error, in your editor and in the build. -To transpile another directory in the same way, add it to [`build.entries`](/docs/guide/modules/module-builder/configuration#directory-entries). +To transpile another directory in the same way, add it to [`builder({ entries })`](/docs/guide/modules/module-builder/configuration#directory-entries). ## `playground/` -A Nuxt app that installs your module, to try it out while you develop it. The starter installs the module by its package name: +A Nuxt app that installs your module, to try it out while you develop it. The playground installs the module by its package name. With pnpm, use the `workspace:` protocol and list `playground` in `pnpm-workspace.yaml`: ```json [playground/package.json] { "dependencies": { - "my-module": "file:.." + "my-module": "workspace:*" } } ``` +With npm, use `"my-module": "file:.."` and list `playground` in the root `workspaces`. + ```ts [playground/nuxt.config.ts] export default defineNuxtConfig({ modules: ['my-module'], @@ -121,11 +124,11 @@ export default defineNuxtConfig({ }) ``` -The playground therefore loads the module through its `package.json` `exports`, from `dist`. A [stub build](/docs/guide/modules/module-builder/commands#build-stub) points `dist` at your sources, so the playground runs them without a full build after every change. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#working-in-the-playground). +The playground therefore loads the module through its `package.json` `exports`. With pnpm or Yarn 4, `exports` point at your sources, and `publishConfig.exports` at `dist` for publishing. With npm, Yarn 3 or earlier, or bun, `exports` point at `dist`, and `tsdown --watch` rebuilds it as you change your sources. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout). ## `package.json` -A minimal `package.json` for a module: +A minimal `package.json` for a module published with pnpm or Yarn 4: ```json [package.json] { @@ -135,18 +138,27 @@ A minimal `package.json` for a module: "type": "module", "exports": { ".": { - "types": "./dist/types.d.mts", - "import": "./dist/module.mjs" + "types": "./.nuxt/module-builder/types.d.mts", + "import": "./src/module.ts" } }, - "main": "./dist/module.mjs", + "main": "./src/module.ts", "files": [ "dist" ], + "publishConfig": { + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + } + }, + "main": "./dist/module.mjs" + }, "scripts": { - "prepack": "nuxt-module-build build", + "prepack": "tsdown", "dev": "nuxt dev playground", - "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground" + "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground" }, "dependencies": { "@nuxt/kit": "^4.0.0" @@ -160,13 +172,35 @@ A minimal `package.json` for a module: } ``` -- `exports["."].types` points at `dist/types.d.mts`, which re-exports the module's types along with the [augmentations](#srcmodulets) above. +- `exports` and `main` point at your sources while you develop. `exports["."].types` points at the declarations that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) writes, which re-export `src/module.ts` along with the [augmentations](#srcmodulets) above. +- `publishConfig` holds the fields that pnpm and Yarn 4 publish in their place. Its `types` condition points at `dist/types.d.mts`, the built equivalent. See [Source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports). - `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. Any other package that the module entry imports, such as a `devDependency`, is bundled into it. -After every build, the builder checks the paths in `exports`, `main`, `module`, `types`, and `typesVersions`, and warns about any that the build didn't produce. +npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point `exports` and `main` at `dist`, leave out `publishConfig`, and build `dist` in `dev:prepare`: + +```json [package.json] +{ + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + } + }, + "main": "./dist/module.mjs", + "scripts": { + "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare playground" + } +} +``` + +Every build checks the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. It fails when one of them points at a TypeScript source or at a file that the pack leaves out, and warns about any that the build didn't produce. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). To publish more entry points, such as `my-module/utils` or `my-module/components`, see [Exports](/docs/guide/modules/module-builder/exports). ## `tsconfig.json` The module's own `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates in the module root. See [TypeScript](/docs/guide/modules/module-builder/typescript). + +## `tsdown.config.ts` + +The build configuration, which adds the `builder()` plugin to tsdown. `tsdown` reads it to build the module. See [Configuration](/docs/guide/modules/module-builder/configuration). From 6c25ec54e537fc38accf6de0f2ad4fa751341b22 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:55:36 +0000 Subject: [PATCH 23/28] docs: set up a module with `tsdown.config.ts` in getting started --- docs/index.md | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/docs/index.md b/docs/index.md index 3c45d33e..91679be9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,9 +5,9 @@ navigation: title: Getting Started --- -`@nuxt/module-builder` builds a Nuxt module for publishing to npm. It bundles the module entry with [tsdown](https://tsdown.dev) and transpiles the runtime directory file by file. It also generates type declarations against the module's own `.nuxt`, and writes the type shims that give `nuxt.config` autocompletion for the module's options. +`@nuxt/module-builder` builds a Nuxt module for publishing to npm. Its `builder()` plugin makes [tsdown](https://tsdown.dev) bundle the module entry and transpile the runtime directory file by file. It also generates type declarations against the module's own `.nuxt`, and writes the type shims that give `nuxt.config` autocompletion for the module's options. -The builder works with the layout of the [module starter](https://github.com/nuxt/starter/tree/module) and needs no configuration for it. To learn how to write the module itself (its definition, hooks, and the `@nuxt/kit` utilities), read the [Module Author Guide](/docs/guide/modules). +The builder works with the layout of the [module starter](https://github.com/nuxt/starter/tree/module) and needs no options for it. To learn how to write the module itself (its definition, hooks, and the `@nuxt/kit` utilities), read the [Module Author Guide](/docs/guide/modules). ## Requirements @@ -55,7 +55,7 @@ npm install npm run dev:prepare ``` -`dev:prepare` stubs the module's `dist` directory and generates the `.nuxt` directories that type the module and its playground. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish) for what each step does. +`dev:prepare` generates the `.nuxt` directories that type the module and its playground. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish) for what each step does. ## Manual installation @@ -65,25 +65,38 @@ Add the builder and its peer dependencies to an existing module: pnpm add -D @nuxt/module-builder tsdown@^0.23.7 typescript nuxt ``` +Add a `tsdown.config.ts` with the `builder()` plugin: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [builder()], +}) +``` + Then add the scripts that build the module before publishing and prepare it for development: ```json [package.json] { "scripts": { - "prepack": "nuxt-module-build build", - "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground" + "prepack": "tsdown", + "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground" } } ``` +This `dev:prepare` suits a module that pnpm or Yarn 4 publishes, with `package.json` pointing at its sources. With npm, Yarn 3 or earlier, or bun, add `tsdown` before `nuxt prepare playground`. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout). + Your module also needs the `exports` and `files` fields described in [Project structure](/docs/guide/modules/module-builder/project-structure#packagejson), and a `tsconfig.json` as described in [TypeScript](/docs/guide/modules/module-builder/typescript). ## Next steps - [Project structure](/docs/guide/modules/module-builder/project-structure): the files the builder reads. -- [Commands](/docs/guide/modules/module-builder/commands): `build`, `build --stub`, and `prepare`. +- [Commands](/docs/guide/modules/module-builder/commands): `tsdown`, `build`, and `prepare`. - [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish): the playground, and releasing to npm. -- [Configuration](/docs/guide/modules/module-builder/configuration): extra entries and directories. +- [Configuration](/docs/guide/modules/module-builder/configuration): `tsdown.config.ts`, extra entries, and directories. - [TypeScript](/docs/guide/modules/module-builder/typescript): the module's `tsconfig.json` and its declarations. - [Build output](/docs/guide/modules/module-builder/output): what ends up in `dist`. - [Exports](/docs/guide/modules/module-builder/exports): subpath exports, including runtime components. From 25a1ab57dbe976fadeb7d9614a818768ec6462bb Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:55:36 +0000 Subject: [PATCH 24/28] docs: describe tsdown builds and source exports in the README --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2e193904..f3ee94d8 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,10 @@ ## Features - Builds modules for Nuxt 3 and later, with no configuration for the [module starter](https://github.com/nuxt/starter/tree/module) layout -- Bundles the module entry with [tsdown](https://tsdown.dev), and transpiles the runtime directory file by file +- Builds with [tsdown](https://tsdown.dev) through the `builder()` plugin: bundles the module entry, and transpiles the runtime directory file by file - Generates declarations against the module's own `.nuxt`, for `.ts` and `.vue` files alike - Writes the type shims that give `nuxt.config` autocompletion for the module's options and hooks -- Stubs `dist` for development, so a playground runs the module's sources directly +- Lets a playground run the module's sources while `package.json` publishes `dist`, and checks the published paths before every build ## Quick start @@ -29,9 +29,9 @@ Building a module requires Node `^22.18.0 || >=24.0.0`, with `tsdown` and `types - [Getting started](./docs/index.md) - [Project structure](./docs/1.project-structure.md) -- [Commands](./docs/2.commands.md): `build`, `build --stub`, and `prepare` -- [Develop and publish](./docs/3.develop-and-publish.md): the playground, and releasing to npm -- [Configuration](./docs/4.configuration.md): extra entries, and the deprecated `build.config.ts` +- [Commands](./docs/2.commands.md): `tsdown`, `build`, and `prepare` +- [Develop and publish](./docs/3.develop-and-publish.md): source exports, the playground, and releasing to npm +- [Configuration](./docs/4.configuration.md): `builder()` in `tsdown.config.ts`, extra entries, and the deprecated `build.config.ts` - [TypeScript](./docs/5.typescript.md): the module's `tsconfig.json`, and its declarations - [Build output](./docs/6.output.md) - [Exports](./docs/7.exports.md): subpath exports, including runtime components From 121f41e5d88435d4ab6e1f36d853e58428c58031 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 13:55:42 +0000 Subject: [PATCH 25/28] docs: attribute the default `transform` to `builder()` --- docs/8.transpile-dir.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/8.transpile-dir.md b/docs/8.transpile-dir.md index 667aed3c..7e5ecbaf 100644 --- a/docs/8.transpile-dir.md +++ b/docs/8.transpile-dir.md @@ -21,7 +21,7 @@ Every file under `srcDir` is emitted under `outBase` in the build's output direc Scripts are transpiled with oxc and keep their imports as written, apart from relative imports, which get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. -By default, scripts are transpiled with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. `nuxt-module-build build` passes the `transform` of the `rolldown` that `tsdown` installs, so a module needs neither. +By default, scripts are transpiled with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. The `builder()` plugin passes the `transform` of the `rolldown` that `tsdown` installs, so a module that builds with it needs neither. ## Options From 79765e4b413f36a80987030d68ed346cd1171cd3 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 14:15:54 +0000 Subject: [PATCH 26/28] docs: cover reading runtime file contents and root `nuxt prepare` with each dev setup --- docs/3.develop-and-publish.md | 4 ++++ docs/upgrade-v2.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index c768f192..6f832793 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -71,6 +71,8 @@ The playground's type check includes your sources and the files they import type There is no `dist` while you develop, so code that reaches into `dist` by path points at `src` instead. Resolve runtime files relative to `src/module.ts` and without an extension, as in `createResolver(import.meta.url).resolve('./runtime/app/plugins/greeting')`. The build keeps the layout of `src` in `dist`, and Nuxt adds the extension. +Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, finds no file at the path without an extension, and TypeScript at the `.ts` path. Generate the template from code that doesn't depend on the built file, or build `dist` first and keep reading from it. + Yarn 4 packs `typesVersions` as written. Keep `typesVersions` at the top level, pointing at `dist`: TypeScript only reads it under `node10` module resolution, which a playground doesn't use. ### Developing against `dist` @@ -103,6 +105,8 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With npm, install the module in the playground with `"my-module": "file:.."` and list `playground` in the root `workspaces`, so npm links the module into the playground. With Yarn 1, use `"my-module": "link:.."`. +`nuxt-module-build prepare` installs the module from its sources even where its own `.nuxtrc` or `nuxt.config` lists it by name. Any other `nuxt prepare` that loads the module by name, such as one at the repository root with `modules[]=my-module` in `.nuxtrc`, loads it from `dist` and leaves it out when `dist` is missing. Run `tsdown` before such a `nuxt prepare` in `dev:prepare`. + While the playground runs, run `tsdown --watch` next to it. It leaves `dist` in place while its first build runs, so the two can start together. Each change under `src` rebuilds `dist`, and a rebuild only writes the files whose content changed. ## Working in the playground diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 36415712..ee3d116b 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -680,6 +680,8 @@ The playground's type check includes the module's sources and the files they imp With source exports there is no `dist` while you develop, so code that reaches into `dist` by path has to point at `src`: a playground or a test that imports `../dist/runtime/...`, or module code that resolves `../dist/runtime/...`. Resolve runtime files relative to `src/module.ts` and without an extension, as `createResolver(import.meta.url).resolve('./runtime/plugins/plugin')` does: the build keeps the layout of `src` in `dist`, and Nuxt and Vite add the extension. +Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, finds no file at the path without an extension, and TypeScript at the `.ts` path. Generate the template from code that doesn't depend on the built file, or build `dist` first and keep reading from it. + A subpath that code outside Nuxt imports, such as a plugin for a plain Vite app, can keep pointing at `dist` in `exports`, so that code loads the built file. Run `tsdown` before using it. Yarn 4 doesn't apply `publishConfig.typesVersions`. Keep `typesVersions` at the top level, pointing at `dist`: TypeScript only reads it under `node10` module resolution, which a playground doesn't use. @@ -737,6 +739,8 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. A playground that installs the module by name lists it as `"my-module": "workspace:*"` or `"my-module": "link:.."`. npm supports neither protocol, so use `"my-module": "file:.."` there, which npm installs as a link. Yarn 1 has no `workspace:` protocol, so use `link:..` there. +`nuxt-module-build prepare` installs the module from its sources even where its own `.nuxtrc` or `nuxt.config` lists it by name. Any other `nuxt prepare` that loads the module by name, such as one at the repository root with `modules[]=my-module` in `.nuxtrc`, loads it from `dist` and leaves it out when `dist` is missing. Run `tsdown` before such a `nuxt prepare` in `dev:prepare`. + While `nuxt dev playground` runs, run `tsdown --watch` next to it. `tsdown --watch` leaves `dist` in place while its first build runs, so the two can start together. Each change under `src` rebuilds `dist`, in about a second for a small module, or less with [isolated declarations](#isolated-declarations). A rebuild only writes the files whose content changed, so the playground updates an edited component in place, and reloads the page for an edited plugin. The playground loads `dist/module.mjs` once, when `nuxt dev` starts: restart `nuxt dev` after changing module code. ## Output size From 20e8bd0ce15a4b8f379b9e37434227939fc8af0f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 14:46:09 +0000 Subject: [PATCH 27/28] docs: fix the size check, type-only import extensions and the `types` field in the guide --- docs/5.typescript.md | 4 ++-- docs/6.output.md | 8 ++++++-- docs/upgrade-v2.md | 23 ++++++++++++----------- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/docs/5.typescript.md b/docs/5.typescript.md index 17733b38..6669da98 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -51,7 +51,7 @@ With [source exports](/docs/guide/modules/module-builder/develop-and-publish#sou The errors this can report, and their fixes: - `#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context, through types that module code imports from a runtime file that uses them: move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. -- Relative imports without extensions (TS2835, TS2834), in a context that resolves imports like Node: add extensions to type-only relative imports as well. +- Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context, which resolves imports like Node when the playground sets `future.compatibilityVersion: 5`: add extensions to type-only relative imports as well. - Globals that the module declares in its own `.d.ts` not found (TS2304), because the playground doesn't include that file: reference it with `/// ` from the files that use the globals. - The module's own aliases not found (TS2307): move an alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`. TypeScript resolves those from the module's files in any project. Declare the types of an alias that the module adds itself, such as a virtual module, with `addTypeTemplate(template, { nuxt: true, node: true })`, so both of the playground's contexts include them. - Other errors in runtime files: fix them, or check the module with the same compiler options. @@ -129,7 +129,7 @@ Without `isolatedDeclarations`, the build prints a reminder once per run outside `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and piece of syntax that breaks these rules, each with its file, line, column, and fix. Until the list is empty, `prepare` doesn't generate `.nuxt`. -Type-only imports don't stop the module from loading, as Node never loads them. Write their extensions too: a type check that resolves imports like Node requires them. Relative imports in other [bundled entries](/docs/guide/modules/module-builder/configuration#bundled-entries) carry their extension as well. Runtime files that module code doesn't import by value keep extensionless imports, as the build adds the extension to their output. +Type-only imports don't stop the module from loading, as Node never loads them. Write their extensions too: a type check that resolves imports like Node requires them, such as the playground's check of its `nuxt.config.ts` context when the playground sets `future.compatibilityVersion: 5`. Relative imports in other [bundled entries](/docs/guide/modules/module-builder/configuration#bundled-entries) carry their extension as well. Runtime files that module code doesn't import by value keep extensionless imports, as the build adds the extension to their output. `erasableSyntaxOnly` makes the type check report the syntax that Node's type stripping can't run: diff --git a/docs/6.output.md b/docs/6.output.md index 8c787bd2..9ef5f736 100644 --- a/docs/6.output.md +++ b/docs/6.output.md @@ -127,8 +127,12 @@ Otherwise, it has a line for each file. `module.json` and `types.d.mts` are writ Set `report` in `tsdown.config.ts` to change it: `{ summary: true }` or `{ summary: false }`, `{ gzip: false }` to skip compressing each file, `{ brotli: true }`, or `false` to turn it off. The lines for each entry and directory follow a summary only. -To check the published size in CI of a module whose `package.json` points at `dist`, `npm pack --dry-run --json` lists what gets published: each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`: +To check the published size in CI, pack the module with the package manager that publishes it, into a temporary directory. Then list the tarball with `npm pack --dry-run --json`, which gives each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`: ```bash [Terminal] -npm pack --dry-run --json | jq '.[0] | { size, unpackedSize, files: [.files[] | { path, size }] }' +pack_dir=$(mktemp -d) +pnpm pack --pack-destination "$pack_dir" +npm pack --dry-run --json "$pack_dir"/*.tgz | jq '.[0] | { size, unpackedSize, files: [.files[] | { path, size }] }' ``` + +With `package.json` pointing at `dist`, `npm pack --pack-destination "$pack_dir"` packs it the same way. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index ee3d116b..da97ae47 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -382,7 +382,7 @@ Both scripts start with `nuxt-module-build prepare`, also where the old one had ## Module code loads with Node -The module's build-time code has to load with Node as it is, because Nuxt 5 loads modules with Node itself. That covers `src/module.ts`, every file it imports by value (runtime files included), `build.config.ts`, and `tsdown.config.ts`. Node strips types and resolves imports as written, so `nuxt-module-build build`, `tsdown`, and `nuxt-module-build prepare` stop with a list of everything it can't load, each with its file, line, column, and fix. A runtime file in the list also names the module code that imports it. Node never loads type-only imports, so they don't stop the module loading, but a type check under `nodenext` module resolution, such as the playground's check of its `nuxt.config.ts`, still requires their extensions: write them with extensions too. Runtime files that module code doesn't import keep extensionless imports, as they're emitted with the extension added. +The module's build-time code has to load with Node as it is, because Nuxt 5 loads modules with Node itself. That covers `src/module.ts`, every file it imports by value (runtime files included), `build.config.ts`, and `tsdown.config.ts`. Node strips types and resolves imports as written, so `nuxt-module-build build`, `tsdown`, and `nuxt-module-build prepare` stop with a list of everything it can't load, each with its file, line, column, and fix. A runtime file in the list also names the module code that imports it. Node never loads type-only imports, so they don't stop the module loading. A type check that resolves imports like Node still requires their extensions, such as the playground's check of its `nuxt.config.ts` context when the playground sets `future.compatibilityVersion: 5`: write them with extensions too. Runtime files that module code doesn't import keep extensionless imports, as they're emitted with the extension added. Set `erasableSyntaxOnly` so your editor and type check report the syntax as well: @@ -636,7 +636,7 @@ Run `dev:prepare` after you install dependencies, and again when the module regi ### Source exports -pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level ones. With either of them, point `exports`, `imports`, `main`, and `types` at `src`, and the same fields in `publishConfig` at `dist`. The playground then loads the module from its sources, with no build. Packing replaces each field as a whole, so `publishConfig.exports` and `publishConfig.imports` repeat every subpath and condition: +pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level ones. With either of them, point `exports`, `imports`, and `main` at `src`, and the same fields in `publishConfig` at `dist`. The playground then loads the module from its sources, with no build. Packing replaces each field as a whole, so `publishConfig.exports` and `publishConfig.imports` repeat every subpath and condition: ```json { @@ -648,7 +648,6 @@ pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level "#shared/*": "./src/runtime/shared/*.ts" }, "main": "./src/module.ts", - "types": "./.nuxt/module-builder/types.d.mts", "publishConfig": { "exports": { ".": { "types": "./dist/types.d.mts", "style": "./dist/runtime/index.css", "default": "./dist/module.mjs" }, @@ -657,8 +656,7 @@ pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level "imports": { "#shared/*": "./dist/runtime/shared/*.js" }, - "main": "./dist/module.mjs", - "types": "./dist/types.d.mts" + "main": "./dist/module.mjs" }, "scripts": { "dev": "nuxt dev playground", @@ -668,12 +666,12 @@ pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level } ``` -`nuxt-module-build prepare` writes `.nuxt/module-builder/types.d.mts`. It re-exports `src/module.ts` and declares the same `#app` and `@nuxt/schema` augmentations as `dist/types.d.mts`, for the module's `ModuleHooks`, `ModuleRuntimeHooks`, `ModuleRuntimeConfig`, and `ModulePublicRuntimeConfig`. The root export's `types` condition and the top-level `types` point at it, so the playground's type check sees the module's hooks and runtime config. A subpath export has no augmentations, so it points at its source. +`nuxt-module-build prepare` writes `.nuxt/module-builder/types.d.mts`. It re-exports `src/module.ts` and declares the same `#app` and `@nuxt/schema` augmentations as `dist/types.d.mts`, for the module's `ModuleHooks`, `ModuleRuntimeHooks`, `ModuleRuntimeConfig`, and `ModulePublicRuntimeConfig`. The root export's `types` condition points at it, so the playground's type check sees the module's hooks and runtime config. A module that supports `node10` consumers also sets `publishConfig.types` to `./dist/types.d.mts` (see [The types field](#the-types-field)). A subpath export has no augmentations, so it points at its source. The playground's type check includes the module's sources and the files they import types from. A built `dist` keeps them out, because declarations aren't checked. The errors this can report, and their fixes: - `#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context, through types that module code imports from a runtime file that uses them: move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. -- Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context, which resolves them like Node: add extensions to type-only relative imports as well. +- Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context, which resolves them like Node when the playground sets `future.compatibilityVersion: 5`: add extensions to type-only relative imports as well. - Globals that the module declares in its own `.d.ts` not found (TS2304), because the playground doesn't include that file: reference it with `/// ` from the files that use the globals. - The module's own aliases not found (TS2307): move an alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`, as TypeScript resolves those from the module's files in any project. Declare the types of an alias that the module adds itself, such as a virtual module, with `addTypeTemplate(template, { nuxt: true, node: true })`, so both of the playground's contexts include them. - Other errors in runtime files, which are checked with the playground's compiler options: fix them, or check the module with the same options. @@ -728,7 +726,6 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. "./utils": { "types": "./dist/utils.d.mts", "default": "./dist/utils.mjs" } }, "main": "./dist/module.mjs", - "types": "./dist/types.d.mts", "scripts": { "dev": "nuxt dev playground", "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare playground", @@ -747,12 +744,16 @@ While `nuxt dev playground` runs, run `tsdown --watch` next to it. `tsdown --wat Every tsdown build reports the size of its output. A module with runtime directories gets a summary, followed by one line for each bundled entry and runtime directory, with the size of its code and of its declarations; others get a line for each file. On a rebuild under `tsdown --watch`, the summary and the per-file lines only count the files that were written, while the lines for each entry and runtime directory cover the whole build. Set `report` in `tsdown.config.ts` to change it: `{ summary: true }` or `{ summary: false }`, `{ gzip: false }` to skip compressing each file, `{ brotli: true }`, or `false` to turn it off. `module.json` and `types.d.mts` are written after the report, so they aren't in it. -To check the published size in CI, `npm pack --dry-run --json` lists exactly what gets published: each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`: +To check the published size in CI, pack the module with the package manager that publishes it, into a temporary directory. Then list the tarball with `npm pack --dry-run --json`, which gives each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`. `pnpm pack --json` lists the files without their sizes. ```bash -npm pack --dry-run --json | jq '.[0] | { size, unpackedSize, files: [.files[] | { path, size }] }' +pack_dir=$(mktemp -d) +pnpm pack --pack-destination "$pack_dir" +npm pack --dry-run --json "$pack_dir"/*.tgz | jq '.[0] | { size, unpackedSize, files: [.files[] | { path, size }] }' ``` +With `package.json` pointing at `dist`, `npm pack --pack-destination "$pack_dir"` packs it the same way. + ## Removed dependencies `unbuild`, `mkdist`, `jiti`, `defu`, and `magic-regexp` are no longer installed with `@nuxt/module-builder`. If your module imports any of them in its own code, add it to the module's own dependencies. @@ -770,7 +771,7 @@ Follow these steps in order to upgrade a module. Each step is mechanical until t 1. Use Node 22.18+ or 24+ locally and in CI. 2. Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`, then `pnpm remove unbuild` (and `mkdist` and `jiti`, if they only served the builder). Do this before step 3. 3. Move the options of `build.config.ts` and of the `build` or `unbuild` field of `package.json` into `builder()` in a `tsdown.config.ts`, as described in [Moving from build.config.ts](#moving-from-buildconfigts), including directory entries such as `{ input: 'src/x/', outDir: 'dist/x' }`. Then delete `build.config.ts` and remove the field. A module without options still gets a `tsdown.config.ts` with `plugins: [builder()]`, so that `tsdown` builds it. -4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. If it does, set `types` to `./dist/types.d.mts`, and give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). +4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. If it does, set `types` to `./dist/types.d.mts` (in `publishConfig` with source exports, see step 8), and give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). 5. Add `"erasableSyntaxOnly": true` to `tsconfig.json`, and rewrite any `enum`, `namespace`, parameter property, or `value` assertion the type check reports. 6. Make module code load with Node, as described in [Module code loads with Node](#module-code-loads-with-node): add the `.ts` extension to relative imports in `src/module.ts` and the files it imports by value, runtime files included (`./utils` becomes `./utils.ts`, `./dir` becomes `./dir/index.ts`), replace value imports through tsconfig `paths` aliases, and move value imports of `#app`, `#imports`, and `#build/*` into runtime files. Do this before step 8: `prepare` lists each problem and doesn't generate `.nuxt` until they're fixed. 7. If the runtime contains `.scss` or `.sass` files, run `pnpm add -D sass`. From b2c4f41277ad49b69e87c01c5b342435588639a8 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 15 Nov 2026 14:47:41 +0000 Subject: [PATCH 28/28] docs: rewrite --- docs/1.project-structure.md | 112 +++++++++++++------ docs/2.commands.md | 74 ++++++++----- docs/3.develop-and-publish.md | 193 +++++++++++++++++++++++++-------- docs/4.configuration.md | 160 +++++++++++++++++++-------- docs/5.typescript.md | 180 +++++++++++++++++++++--------- docs/6.output.md | 45 ++++++-- docs/7.exports.md | 66 +++++++++-- docs/8.transpile-dir.md | 60 ++++++++-- docs/cli/build-module/index.md | 4 +- docs/index.md | 74 +++++++------ docs/upgrade-v2.md | 105 ++++++++++++++---- 11 files changed, 782 insertions(+), 291 deletions(-) diff --git a/docs/1.project-structure.md b/docs/1.project-structure.md index ec75d301..70d7d8e9 100644 --- a/docs/1.project-structure.md +++ b/docs/1.project-structure.md @@ -3,7 +3,7 @@ title: Project Structure description: The files and directories that `@nuxt/module-builder` reads. --- -The builder works with this layout: +`@nuxt/module-builder` builds a module with this layout: ```bash my-module/ @@ -18,15 +18,17 @@ my-module/ โ””โ”€โ”€ tsdown.config.ts # the build configuration ``` +This page describes what each of these files and directories contains. + ## `src/module.ts` -The module entry. Its default export is the module definition, created with `defineNuxtModule` from `@nuxt/kit`. The build bundles it into `dist/module.mjs`. +`src/module.ts` is the module entry. Its default export is the module definition, which you create with `defineNuxtModule` from `@nuxt/kit`. The build bundles it into `dist/module.mjs`. -The builder also reads these type exports, and adds them to the types of the app that installs the module: +The build also reads these type exports, and adds them to the types of the app that installs the module: | Export | Augments | Used for | |---|---|---| -| `ModuleOptions` | | The module's key in `nuxt.config`. When it isn't exported, it's inferred from the default export. | +| `ModuleOptions` | | The module's key in `nuxt.config`. When you don't export it, it's inferred from the default export. | | `ModuleHooks` | `NuxtHooks` from `@nuxt/schema` | Build-time hooks the module calls, which apps and other modules register with `hooks` or `nuxt.hook()`. | | `ModuleRuntimeHooks` | `RuntimeNuxtHooks` from `#app` | Runtime hooks the module calls, which plugins register with `nuxtApp.hook()`. | | `ModuleRuntimeConfig` | `RuntimeConfig` from `@nuxt/schema` | Private runtime config keys the module adds. | @@ -60,6 +62,7 @@ export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule', + compatibility: { nuxt: '>=4.0.0' }, }, defaults: { greeting: 'Hello', @@ -77,26 +80,45 @@ export default defineNuxtModule({ }) ``` -[`prepare`](/docs/guide/modules/module-builder/commands#prepare) and the build load `src/module.ts`, and every file it imports by value, with Node. Relative imports in these files carry the imported file's extension, `./utils.ts` rather than `./utils`, and the files use only syntax that Node's type stripping removes. See [Module code](/docs/guide/modules/module-builder/typescript#module-code) for all the rules. +### Module code loads with Node + +[`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) and the build load `src/module.ts` with Node, together with every file that it imports by value. Node resolves imports as written, so relative imports in these files carry the imported file's extension: + +```ts [src/module.ts] +import { defineNuxtModule } from '@nuxt/kit' +import { resolveOptions } from './options.ts' +``` + +These files also use only the TypeScript syntax that Node's type stripping removes. [Module code](/docs/guide/modules/module-builder/typescript#module-code) lists all the rules. + +### Paths into the runtime directory -Paths into the runtime directory, such as the one passed to `addPlugin` above, are written without an extension. `src/runtime/app/plugins/greeting.ts` is emitted as `dist/runtime/app/plugins/greeting.js`. Nuxt resolves a path without an extension to the file that exists. That's the `.ts` source when `package.json` points at your sources, and the `.js` output from `dist`. +Write paths into the runtime directory without an extension, as in the `addPlugin` call above. The build emits `src/runtime/app/plugins/greeting.ts` as `dist/runtime/app/plugins/greeting.js`. Nuxt resolves a path without an extension to the file that exists: the `.ts` source when `package.json` points at your sources, and the `.js` output when it points at `dist`. ## `src/runtime/` -Code that the module adds to the app: components, composables, plugins, server routes, stylesheets, and any other files. The module registers them from `setup()`, with utilities such as `addPlugin`, `addComponent`, or `addServerHandler`. +The runtime directory holds the code that the module adds to the app: components, composables, plugins, server routes, stylesheets, and any other files. The module registers them from `setup()`, with `@nuxt/kit` utilities such as `addPlugin`, `addComponent`, `addImports`, and `addServerHandler`. -Put code for the app in `src/runtime/app/`, and code for the server in `src/runtime/server/`. In an app that installs the module, Nuxt type-checks `runtime/server/` in the server context and the rest of `runtime/` in the app context. The module's own `tsconfig.json` type-checks all of `src/runtime/` with one configuration. See [Augment Types](/docs/guide/modules/recipes-advanced#augment-types) in the Module Author Guide. +Put code for the app in `src/runtime/app/`, and code for the server in `src/runtime/server/`. In an app that installs the module, Nuxt type-checks `runtime/server/` in the server context, and the rest of `runtime/` in the app context. Your module's own `tsconfig.json` type-checks all of `src/runtime/` with one configuration. See [Augment Types](/docs/guide/modules/recipes-advanced#augment-types) in the Module Author Guide. -Each file is transpiled on its own into `dist/runtime/`, keeping its name and its imports. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. +The build transpiles each file on its own into `dist/runtime/`, and keeps its name and its imports. [Build Output](/docs/guide/modules/module-builder/output#runtime-files) describes how each kind of file is emitted. -Files in the runtime directory can't rely on auto-imports, since Nuxt doesn't apply them to files in `node_modules`. Import what you use from `#imports`, or from the package that provides it: +### Imports in runtime files -```ts [src/runtime/app/composables/useGreeting.ts] -import { useRuntimeConfig } from '#imports' +Nuxt doesn't apply auto-imports to files in `node_modules`, so runtime files can't rely on them. Import what you use from `#imports`, or from the package that provides it: -export function useGreeting() { - return `${useRuntimeConfig().public.myModule.greeting} from my-module` -} +```ts [src/runtime/app/plugins/greeting.ts] +import { defineNuxtPlugin, useRuntimeConfig } from '#imports' + +export default defineNuxtPlugin(() => { + const { greeting } = useRuntimeConfig().public.myModule + + return { + provide: { + greet: (name: string) => `${greeting}, ${name}!`, + }, + } +}) ``` The `.nuxt` that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) generates for your module disables auto-imports too. A missing import is then a type error, in your editor and in the build. @@ -105,7 +127,18 @@ To transpile another directory in the same way, add it to [`builder({ entries }) ## `playground/` -A Nuxt app that installs your module, to try it out while you develop it. The playground installs the module by its package name. With pnpm, use the `workspace:` protocol and list `playground` in `pnpm-workspace.yaml`: +The playground is a Nuxt app that installs your module, so you can try the module while you develop it. It installs the module by its package name: + +```ts [playground/nuxt.config.ts] +export default defineNuxtConfig({ + modules: ['my-module'], + myModule: { + greeting: 'Hi', + }, +}) +``` + +The playground has to resolve that name to the module directory. With pnpm, list `playground` in `pnpm-workspace.yaml` and use the `workspace:` protocol: ```json [playground/package.json] { @@ -115,20 +148,13 @@ A Nuxt app that installs your module, to try it out while you develop it. The pl } ``` -With npm, use `"my-module": "file:.."` and list `playground` in the root `workspaces`. +With npm, list `playground` in the root `workspaces` and use `"my-module": "file:.."`. -```ts [playground/nuxt.config.ts] -export default defineNuxtConfig({ - modules: ['my-module'], - myModule: {}, -}) -``` - -The playground therefore loads the module through its `package.json` `exports`. With pnpm or Yarn 4, `exports` point at your sources, and `publishConfig.exports` at `dist` for publishing. With npm, Yarn 3 or earlier, or bun, `exports` point at `dist`, and `tsdown --watch` rebuilds it as you change your sources. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout). +The playground loads the module through the `exports` of `package.json`. With pnpm or Yarn 4, `exports` point at your sources, and `publishConfig.exports` point at `dist` for publishing. With npm, Yarn 3 or earlier, or bun, `exports` point at `dist`, and `tsdown --watch` rebuilds `dist` as you change your sources. [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout) describes both setups. ## `package.json` -A minimal `package.json` for a module published with pnpm or Yarn 4: +This is a minimal `package.json` for a module that you publish with pnpm or Yarn 4: ```json [package.json] { @@ -172,11 +198,11 @@ A minimal `package.json` for a module published with pnpm or Yarn 4: } ``` -- `exports` and `main` point at your sources while you develop. `exports["."].types` points at the declarations that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) writes, which re-export `src/module.ts` along with the [augmentations](#srcmodulets) above. -- `publishConfig` holds the fields that pnpm and Yarn 4 publish in their place. Its `types` condition points at `dist/types.d.mts`, the built equivalent. See [Source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports). -- `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. Any other package that the module entry imports, such as a `devDependency`, is bundled into it. +- `exports` and `main` point at your sources while you develop. `exports["."].types` points at the declarations that [`prepare`](/docs/guide/modules/module-builder/commands#prepare) writes. They re-export `src/module.ts`, together with the [augmentations](#srcmodulets) above. +- `publishConfig` holds the fields that pnpm and Yarn 4 publish in place of the top-level ones. Its `types` condition points at `dist/types.d.mts`, the built equivalent. See [Source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports). +- `dependencies`, `peerDependencies`, and `optionalDependencies` stay external to `dist/module.mjs`. The build bundles any other package that the module entry imports, such as a `devDependency`. -npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point `exports` and `main` at `dist`, leave out `publishConfig`, and build `dist` in `dev:prepare`: +npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. If you publish with one of them, point `exports` and `main` at `dist`, leave out `publishConfig`, and build `dist` in `dev:prepare`: ```json [package.json] { @@ -193,14 +219,34 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. } ``` -Every build checks the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. It fails when one of them points at a TypeScript source or at a file that the pack leaves out, and warns about any that the build didn't produce. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). +Every build reads the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. The build fails when one of them points at a TypeScript source, or at a file that the pack leaves out. It warns about any path that the build didn't produce. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). To publish more entry points, such as `my-module/utils` or `my-module/components`, see [Exports](/docs/guide/modules/module-builder/exports). ## `tsconfig.json` -The module's own `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates in the module root. See [TypeScript](/docs/guide/modules/module-builder/typescript). +Your module's own `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates in the module root: + +```json [tsconfig.json] +{ + "extends": "./.nuxt/tsconfig.json", + "exclude": ["dist", "node_modules", "playground"] +} +``` + +[TypeScript](/docs/guide/modules/module-builder/typescript) describes this setup. ## `tsdown.config.ts` -The build configuration, which adds the `builder()` plugin to tsdown. `tsdown` reads it to build the module. See [Configuration](/docs/guide/modules/module-builder/configuration). +`tsdown.config.ts` is the build configuration. It adds the `builder()` plugin to tsdown: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [builder()], +}) +``` + +`tsdown` and `nuxt-module-build build` both read it. [Configuration](/docs/guide/modules/module-builder/configuration) lists its options. diff --git a/docs/2.commands.md b/docs/2.commands.md index 444824d0..8db0ab03 100644 --- a/docs/2.commands.md +++ b/docs/2.commands.md @@ -8,9 +8,14 @@ links: size: xs --- -A module builds with `tsdown`, through the [`builder()` plugin](/docs/guide/modules/module-builder/configuration) in its `tsdown.config.ts`. `@nuxt/module-builder` also installs the `nuxt-module-build` command, which has two subcommands: `build` and `prepare`. Name the subcommand every time: `nuxt-module-build` without one runs `build` and prints a warning. +You build a module with `tsdown`, which reads the [`builder()` plugin](/docs/guide/modules/module-builder/configuration) from your `tsdown.config.ts`. `@nuxt/module-builder` also installs the `nuxt-module-build` command, with two subcommands: -The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/build-module): `nuxt build-module build` is `nuxt-module-build build`. To see how a module's scripts combine them, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). +- `build` builds the module, with or without a `tsdown.config.ts`. +- `prepare` generates the `.nuxt` directory that types the module. + +Name the subcommand every time. `nuxt-module-build` without a subcommand runs `build` and prints a warning. + +The Nuxt CLI runs the same subcommands as [`nuxt build-module`](/docs/api/commands/build-module), so `nuxt build-module build` is the same as `nuxt-module-build build`. To see how a module's scripts combine these commands, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). ## `tsdown` @@ -18,7 +23,7 @@ The Nuxt CLI runs the same commands as [`nuxt build-module`](/docs/api/commands/ npx tsdown [--outDir=] [--sourcemap] [--watch] ``` -Builds the module for publishing with its `tsdown.config.ts`. This is the command that the `prepack` script runs: +`tsdown` builds the module for publishing with its `tsdown.config.ts`. Run it from the `prepack` script, so the package manager builds the module whenever it packs or publishes it: ```json [package.json] { @@ -28,9 +33,17 @@ Builds the module for publishing with its `tsdown.config.ts`. This is the comman } ``` -`tsdown` needs a `tsdown.config.ts` that uses `builder()`. Without one, it doesn't build the module. The build runs the steps described in [`build`](#build), and tsdown's own options, such as `--outDir` and `--sourcemap`, take precedence over the config. +`tsdown` needs a `tsdown.config.ts` that uses `builder()`. Without one, it doesn't build the module. It runs the same steps as [`build`](#build). tsdown's own options, such as `--outDir` and `--sourcemap`, take precedence over the config. + +### Watch mode -`tsdown --watch` builds the module, then rebuilds it when a source file changes, including the files that `src/module.ts` imports and files added to the runtime directory. It leaves the output directory in place while its first build runs. A rebuild only writes the files whose content changed, and removes the files that the build no longer emits. See [Developing against `dist`](/docs/guide/modules/module-builder/develop-and-publish#developing-against-dist). +`tsdown --watch` builds the module, then rebuilds it when a source file changes. That includes the files that `src/module.ts` imports, and new files in the runtime directory: + +```bash [Terminal] +npx tsdown --watch +``` + +Watch mode keeps the output directory in place while its first build runs. A rebuild only writes the files whose content changed, and removes the files that the build doesn't emit any more. See [Developing against `dist`](/docs/guide/modules/module-builder/develop-and-publish#developing-against-dist). ## `build` @@ -38,24 +51,27 @@ Builds the module for publishing with its `tsdown.config.ts`. This is the comman npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] ``` -Builds the module for publishing, with the same output, checks, and warnings as `tsdown`. With a `tsdown.config.ts`, it builds with that config. Without one, it builds `src/module.ts` and `src/runtime/`, plus the entries in the [`build` field of `package.json`](/docs/guide/modules/module-builder/configuration#without-a-tsdown-config), so a module needs no configuration file. +`build` builds the module for publishing. It produces the same output, checks, and warnings as `tsdown`: + +- With a `tsdown.config.ts`, it builds with that config. +- Without one, it builds `src/module.ts` and `src/runtime/`, plus the entries in the [`build` field of `package.json`](/docs/guide/modules/module-builder/configuration#without-a-tsdown-config). A module then needs no configuration file. -Both commands run these steps: +### Build steps -1. It checks the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. When it runs as the `prepack` or `prepublishOnly` script, it also checks that the package manager that packs applies `publishConfig`. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). -2. If `.nuxt/tsconfig.json` is missing from the module root, it runs [`prepare`](#prepare) first. -3. It reads the [build configuration](/docs/guide/modules/module-builder/configuration) and checks that the module code loads with Node. See [Module code](/docs/guide/modules/module-builder/typescript#module-code). -4. It empties the output directory. -5. It bundles `src/module.ts`, and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries), with tsdown. -6. It transpiles `src/runtime/`, and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries), file by file. -7. It generates the declarations of every entry and runtime file, using the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). -8. It prints the [size of the output](/docs/guide/modules/module-builder/output#size-report). -9. It loads the built module to write `dist/module.json`, and writes `dist/types.d.mts`. -10. It checks the paths in `package.json` against the files it produced. +`tsdown` and `build` both run these steps: -The build fails when a declaration can't be generated correctly. Other type errors are reported as warnings. See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) for both. +1. Check the paths that `package.json` publishes, with the fields of `publishConfig` in place of the top-level ones. As the `prepack` or `prepublishOnly` script, also check that the package manager that packs applies `publishConfig`. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). +2. Run [`prepare`](#prepare) first, if `.nuxt/tsconfig.json` is missing from the module root. +3. Read the [build configuration](/docs/guide/modules/module-builder/configuration), and check that the module code loads with Node. See [Module code](/docs/guide/modules/module-builder/typescript#module-code). +4. Empty the output directory. +5. Bundle `src/module.ts` and any other [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entries) with tsdown. +6. Transpile `src/runtime/` and any other [directory entry](/docs/guide/modules/module-builder/configuration#directory-entries) file by file. +7. Generate the declarations of every entry and runtime file, with the [module's `tsconfig.json`](/docs/guide/modules/module-builder/typescript). +8. Print the [size of the output](/docs/guide/modules/module-builder/output#size-report). +9. Load the built module to write `dist/module.json`, and write `dist/types.d.mts`. +10. Compare the paths in `package.json` with the files that the build produced. -See [Build output](/docs/guide/modules/module-builder/output) for the files the build writes. +The build fails when it can't generate a declaration correctly. It reports other type errors as warnings. [TypeScript](/docs/guide/modules/module-builder/typescript#declarations) describes both. [Build Output](/docs/guide/modules/module-builder/output) lists the files that the build writes. ### Arguments @@ -68,7 +84,7 @@ See [Build output](/docs/guide/modules/module-builder/output) for the files the | Option | Default | Description | |---|---|---| | `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | -| `--outDir=` | | The output directory, relative to the module root. Takes precedence over `outDir` in the tsdown config, which defaults to `dist`. It's emptied before every build, so it must be inside the module. | +| `--outDir=` | | The output directory, relative to the module root. Takes precedence over `outDir` in the tsdown config, which defaults to `dist`. The build empties it first, so it must be inside the module. | | `--sourcemap` | | Emit a source map next to every script. Takes precedence over `sourcemap` in the tsdown config. | ## `prepare` @@ -77,15 +93,23 @@ See [Build output](/docs/guide/modules/module-builder/output) for the files the npx nuxt-module-build prepare [ROOTDIR] [--cwd=] ``` -Generates `.nuxt` in the module root. It runs `nuxt prepare` on the module root, as a Nuxt app with your module as its only module and auto-imports disabled. It writes nothing to `dist`. +`prepare` generates `.nuxt` in the module root. It runs `nuxt prepare` on the module root, as a Nuxt app with your module as its only module and with auto-imports disabled. It writes nothing to `dist`. + +Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` that `prepare` generates. Your editor, your type check, and the declarations that the build generates then see the same types: + +- `@nuxt/schema`. +- The `#app`, `#imports`, and `#build` aliases. +- Anything your module adds, such as its templates and its server routes. + +`prepare` also writes `.nuxt/module-builder/types.d.mts`. This file re-exports `src/module.ts`, and adds the same [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) as `dist/types.d.mts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it. -Your module's `tsconfig.json` extends the `.nuxt/tsconfig.json` it generates. That gives your editor, your type check, and the declarations that the build generates the same types: `@nuxt/schema`, the `#app`, `#imports`, and `#build` aliases, and anything your module adds, such as its templates and server routes. See [TypeScript](/docs/guide/modules/module-builder/typescript). +### How `prepare` loads your module -It also writes `.nuxt/module-builder/types.d.mts`, which re-exports `src/module.ts` and adds the same [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) as `dist/types.d.mts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it. +`prepare` loads `src/module.ts` with Node. It also reads the options of `builder()` from `tsdown.config.ts`, which it loads with Node too. Your module code therefore follows the rules in [Module code](/docs/guide/modules/module-builder/typescript#module-code). Until it does, `prepare` lists each problem and doesn't generate `.nuxt`. -`prepare` loads `src/module.ts` with Node, and reads the options of `builder()` from `tsdown.config.ts`, which it loads with Node too. Module code therefore follows the rules in [Module code](/docs/guide/modules/module-builder/typescript#module-code). Until it does, `prepare` lists each problem and doesn't generate `.nuxt`. `prepare` fails when the tsdown config sets `cwd` to another directory. tsdown's hooks and plugins don't run for `prepare`. +`prepare` fails when the tsdown config sets `cwd` to another directory. tsdown's hooks and plugins don't run for `prepare`. -Run `prepare` again after a change to anything the module registers for types: its options, templates, type declarations, or server routes. +Run `prepare` again after you change anything that the module registers for types: its options, templates, type declarations, or server routes. ### Arguments diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md index 6f832793..8f72c451 100644 --- a/docs/3.develop-and-publish.md +++ b/docs/3.develop-and-publish.md @@ -3,16 +3,22 @@ title: Develop and Publish description: Prepare a checkout, work on the module in its playground, and publish it to npm. --- -A module has a script for each stage of its life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each one does. To create a module from the starter, see [Getting Started](/docs/guide/modules/module-builder). To move a module that used stub builds, see [Stub builds](/docs/guide/modules/module-builder/upgrade-v2#stub-builds) in the upgrade guide. +A module has a script for each stage of its life: preparing a fresh checkout, running the playground, and publishing a release. This page describes what each script does, and the two development setups that they depend on. + +To create a module from the starter, see [Getting Started](/docs/guide/modules/module-builder). To move a module that used stub builds in v1, see [Stub builds](/docs/guide/modules/module-builder/upgrade-v2#stub-builds) in the upgrade guide. ## Preparing a checkout -The [playground](/docs/guide/modules/module-builder/project-structure#playground) installs the module by its package name, so it loads whatever `package.json` points at. Which setup to use depends on the package manager that publishes the module: +The [playground](/docs/guide/modules/module-builder/project-structure#playground) installs the module by its package name, so it loads whatever `package.json` points at. The package manager that publishes your module decides which setup you use: + +| Package manager | `package.json` points at | While you develop | +|---|---|---| +| pnpm, Yarn 4 | Your sources, with the `dist` paths in `publishConfig` | The playground runs your sources. See [Source exports](#source-exports). | +| npm, Yarn 3 and earlier, bun | `dist` | `tsdown --watch` rebuilds `dist`. See [Developing against `dist`](#developing-against-dist). | -- With pnpm or Yarn 4, `package.json` points at your sources, and `publishConfig` holds the `dist` paths that are published. The playground runs your sources, and `dist` is only written when you build. See [Source exports](#source-exports). -- With npm, Yarn 3 or earlier, or bun, `package.json` points at `dist`, and `tsdown --watch` rebuilds it while you develop. See [Developing against `dist`](#developing-against-dist). +Run `dev:prepare` after you install dependencies. Run it again when the types that it generates are out of date, such as after the module registers a new template or server route. -Run `dev:prepare` after you install dependencies, and again when the types it generates are out of date, such as after the module registers a new template or server route. The build runs `prepare` on its own when `.nuxt` is missing. Keeping `prepare` in `dev:prepare` puts the module's types in place before your editor or type check needs them. +The build runs `prepare` on its own when `.nuxt` is missing. Keep `prepare` in `dev:prepare` anyway, so the module's types are in place before your editor or your type check needs them. ### Source exports @@ -47,12 +53,14 @@ pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level } ``` -1. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`, and the `.nuxt/module-builder/types.d.mts` that the root export's `types` condition points at. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +`dev:prepare` runs two commands: + +1. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. It also writes the `.nuxt/module-builder/types.d.mts` that the root export's `types` condition points at. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). 2. `nuxt prepare playground` generates the playground's `.nuxt`. It loads `src/module.ts` through `exports`. -`publishConfig` replaces each field as a whole, so `publishConfig.exports` repeats every subpath and condition of `exports`. See [Exports](/docs/guide/modules/module-builder/exports#source-exports) for subpaths. +`publishConfig` replaces each field as a whole, so `publishConfig.exports` repeats every subpath and condition of `exports`. [Exports](/docs/guide/modules/module-builder/exports#source-exports) shows an example with subpaths. -The playground has to resolve the module's name to the module directory itself. With pnpm, install it with `workspace:*` and list `playground` in `pnpm-workspace.yaml`, or with `link:..`: +The playground has to resolve the module's name to the module directory itself. With pnpm, list `playground` in `pnpm-workspace.yaml`, and install the module with `workspace:*` or `link:..`: ```yaml [pnpm-workspace.yaml] packages: @@ -67,17 +75,51 @@ packages: } ``` -The playground's type check includes your sources and the files they import types from. See [The playground's `tsconfig.json`](/docs/guide/modules/module-builder/typescript#with-source-exports) for the errors this can report. +The playground's type check includes your sources and the files that they import types from. [The playground's `tsconfig.json`](/docs/guide/modules/module-builder/typescript#with-source-exports) lists the errors that this can report. + +Yarn 4 packs `typesVersions` as written. Keep `typesVersions` at the top level, pointing at `dist`. TypeScript only reads it under `node10` module resolution, which a playground doesn't use. + +#### Code that reaches into `dist` + +There is no `dist` while you develop, so code that reaches into `dist` by path has to point at `src`. Resolve runtime files relative to `src/module.ts`, without an extension: + +```ts [src/module.ts] +import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addPlugin(resolver.resolve('./runtime/app/plugins/greeting')) + }, +}) +``` + +The build keeps the layout of `src` in `dist`, and Nuxt adds the extension. + +Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, needs more care. It finds no file at the path without an extension, and TypeScript at the `.ts` path. Generate the template from code that doesn't depend on the built file: -There is no `dist` while you develop, so code that reaches into `dist` by path points at `src` instead. Resolve runtime files relative to `src/module.ts` and without an extension, as in `createResolver(import.meta.url).resolve('./runtime/app/plugins/greeting')`. The build keeps the layout of `src` in `dist`, and Nuxt adds the extension. +```ts [src/module.ts] +import { addTemplate, defineNuxtModule } from '@nuxt/kit' -Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, finds no file at the path without an extension, and TypeScript at the `.ts` path. Generate the template from code that doesn't depend on the built file, or build `dist` first and keep reading from it. +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + defaults: { languages: ['ts', 'vue'] }, + setup(options) { + addTemplate({ + filename: 'my-module/languages.mjs', + getContents: () => `export const languages = ${JSON.stringify(options.languages)}`, + }) + }, +}) +``` -Yarn 4 packs `typesVersions` as written. Keep `typesVersions` at the top level, pointing at `dist`: TypeScript only reads it under `node10` module resolution, which a playground doesn't use. +If the template has to contain the built file, build `dist` first and keep reading from `dist`. ### Developing against `dist` -npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point `package.json` at `dist`, and build it before the playground is prepared: +npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. With them, point `package.json` at `dist`, and build `dist` before the playground is prepared: ```json [package.json] { @@ -99,49 +141,89 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. } ``` +`dev:prepare` runs three commands: + 1. `nuxt-module-build prepare` generates the module's own `.nuxt`, for the module's `tsconfig.json`. 2. `tsdown` builds `dist`. See [`tsdown`](/docs/guide/modules/module-builder/commands#tsdown). 3. `nuxt prepare playground` generates the playground's `.nuxt`. It loads `dist/module.mjs` through `exports`. -With npm, install the module in the playground with `"my-module": "file:.."` and list `playground` in the root `workspaces`, so npm links the module into the playground. With Yarn 1, use `"my-module": "link:.."`. +With npm, list `playground` in the root `workspaces`, and install the module in the playground with `"my-module": "file:.."`. npm then links the module into the playground. With Yarn 1, use `"my-module": "link:.."`. + +While the playground runs, run `tsdown --watch` next to it: + +```bash [Terminal] +npx tsdown --watch +``` + +Watch mode keeps `dist` in place while its first build runs, so you can start both at the same time. Each change under `src` rebuilds `dist`, and a rebuild only writes the files whose content changed. + +#### Other `nuxt prepare` commands -`nuxt-module-build prepare` installs the module from its sources even where its own `.nuxtrc` or `nuxt.config` lists it by name. Any other `nuxt prepare` that loads the module by name, such as one at the repository root with `modules[]=my-module` in `.nuxtrc`, loads it from `dist` and leaves it out when `dist` is missing. Run `tsdown` before such a `nuxt prepare` in `dev:prepare`. +`nuxt-module-build prepare` installs the module from its sources, even where the module's own `.nuxtrc` or `nuxt.config` lists it by name. Any other `nuxt prepare` that loads the module by name loads it from `dist`, and leaves the module out when `dist` is missing. One example is a `nuxt prepare` at the repository root, with `modules[]=my-module` in its `.nuxtrc`. Run `tsdown` before such a command: -While the playground runs, run `tsdown --watch` next to it. It leaves `dist` in place while its first build runs, so the two can start together. Each change under `src` rebuilds `dist`, and a rebuild only writes the files whose content changed. +```json [package.json] +{ + "scripts": { + "dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare && nuxt prepare playground" + } +} +``` ## Working in the playground -The playground is a Nuxt app that installs your module, so you can try it out as you change it: +The playground is a Nuxt app that installs your module, so you can try the module as you change it: - `npm run dev` starts the playground's development server with `nuxt dev playground`. -- `npm run dev:build` builds the playground with `nuxt build playground`. +- `nuxt build playground` builds the playground. - Any other `nuxt` command works against the playground too, as `nuxt playground`. -Nuxt serves the files of the runtime directory through Vite, so an edited component updates in place, and an edited plugin reloads the page. With `dist`, this applies once `tsdown --watch` has rebuilt the file. The playground loads the module itself once, when `nuxt dev` starts: restart `nuxt dev` after you change `src/module.ts` or the files it imports. +Nuxt serves the files of the runtime directory through Vite. An edited component updates in place, and an edited plugin reloads the page. When the playground runs `dist`, this happens after `tsdown --watch` rebuilds the file. + +The playground loads the module itself once, when `nuxt dev` starts. Restart `nuxt dev` after you change `src/module.ts` or the files that it imports. -With source exports, the playground always runs your sources. With `package.json` pointing at `dist`, it runs the last build. To try the output of a full build there, build the module and start the playground: +With source exports, the playground always runs your sources. When `package.json` points at `dist`, the playground runs the last build. To try a full build there, build the module and start the playground: -```bash +```bash [Terminal] npx tsdown && npx nuxt dev playground ``` -See [Testing](/docs/guide/modules/testing) in the Module Author Guide for the tests themselves. +For the module's tests, see [Testing](/docs/guide/modules/testing) in the Module Author Guide. ## Publishing -The `prepack` script runs `tsdown`, so the package manager builds the module whenever it packs or publishes it. You don't need to build it yourself first. +The `prepack` script runs `tsdown`, so the package manager builds the module whenever it packs or publishes it. You don't need to build the module yourself first. -Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. To check the package before you publish it, pack the module with the package manager that publishes it, such as `pnpm pack` for source exports. Then run [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: +Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. -```bash -pnpm pack -npx publint ./my-module-1.0.0.tgz -npx @arethetypeswrong/cli ./my-module-1.0.0.tgz -``` +### Checking the package -A `release` script can publish a new version in one step: +To check the package before you publish it, follow these steps: -```json [package.json] +1. Pack the module with the package manager that publishes it, such as `pnpm pack` for source exports: + + ```bash [Terminal] + pnpm pack + ``` + +2. Run [publint](https://publint.dev) on the tarball: + + ```bash [Terminal] + npx publint ./my-module-1.0.0.tgz + ``` + +3. Run [Are the Types Wrong?](https://arethetypeswrong.github.io) on the tarball: + + ```bash [Terminal] + npx @arethetypeswrong/cli ./my-module-1.0.0.tgz + ``` + +### Releasing a version + +A `release` script can publish a new version in one step. Use the package manager that applies your setup: + +::code-group + +```json [Source exports] { "scripts": { "release": "pnpm lint && pnpm test && pnpm prepack && changelogen --release && pnpm publish && git push --follow-tags" @@ -149,31 +231,56 @@ A `release` script can publish a new version in one step: } ``` -1. It runs the linter, the tests, and the build. The release stops if any of them fails. -2. `changelogen --release` bumps the version, updates `CHANGELOG.md` from your commit messages, and commits and tags the result. -3. `pnpm publish` publishes the package. `prepack` builds the module again, so `dist` has the new version. -4. `git push --follow-tags` pushes the release commit and its tag. +```json [dist] +{ + "scripts": { + "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags" + } +} +``` + +:: + +The script runs these steps: -With source exports, publish with `pnpm publish` or `yarn npm publish`. With `dist`, `npm publish` works too. +1. Run the linter, the tests, and the build. The release stops if any of them fails. +2. Run `changelogen --release`, which bumps the version, updates `CHANGELOG.md` from your commit messages, and commits and tags the result. +3. Publish the package. `prepack` builds the module again, so `dist` has the new version. +4. Push the release commit and its tag with `git push --follow-tags`. Commit your changes before you run `release`. `changelogen` reads [Conventional Commits](https://www.conventionalcommits.org) to choose the version bump and to write the changelog. +With source exports, publish with `pnpm publish` or `yarn npm publish`. A `release` script that runs `npm publish` fails, even when `pnpm run` starts it. `npm publish` of a tarball that `pnpm pack` wrote works, because its `package.json` already has the `dist` paths, and the build doesn't run again. + ### Checks on published paths -Every build reads the path fields of `package.json`, such as `exports`, `main`, and `types`, with the fields of `publishConfig` in place of the top-level ones. It fails before building when one of them points at a path that doesn't work once the package is installed: +Every build reads the path fields of `package.json`, such as `exports`, `main`, and `types`. It reads them with the fields of `publishConfig` in place of the top-level ones. The build fails before it starts when one of them points at a path that doesn't work once the package is installed: - A TypeScript source other than a declaration, which Node doesn't load from `node_modules`. - A path that the pack leaves out, because `files` doesn't list it. Without `files`, a path into `.nuxt` counts as left out. -Every pack includes `package.json` and the file that `main` points at, so `files` doesn't have to list them. To publish a file other than a TypeScript source as it is, list it in `files`. +Every pack includes `package.json` and the file that `main` points at, so `files` doesn't have to list them. To publish a file other than a TypeScript source as it is, list it in `files`: + +```json [package.json] +{ + "files": ["dist", ".nuxt/my-module.css"], + "imports": { + "#my-module/styles.css": "./.nuxt/my-module.css" + } +} +``` + +The build checks an entry of `imports` in the same way once the build is done, and only when the build output imports it. An entry that the build bundles into `module.mjs` can keep pointing at `src`. + +### Checks when you pack -An entry of `imports` is checked in the same way once the build is done, and only when the build output imports it. An entry that the build bundles into `module.mjs` can keep pointing at `src`. +When `tsdown` or `nuxt-module-build build` runs as the `prepack` or `prepublishOnly` script, the build also checks how the package manager packs `package.json`. It fails when the package manager would publish a path that points at your sources: -When `tsdown` or `nuxt-module-build build` runs as the `prepack` or `prepublishOnly` script, the build also fails when the package manager that packs would publish such a path as written: +- The package manager has to apply `publishConfig` to each field that points at your sources. pnpm applies it to all of them. Yarn 4 applies it to every field except `typesVersions`. Yarn 3 applies it to `exports`, `imports`, `main`, and `module`, and Yarn 2 to `main` and `module`. npm, Yarn 1, and bun pack `package.json` as written. +- `publishConfig` has to set each of those fields, to paths that pass the [checks on published paths](#checks-on-published-paths). -- The package manager has to apply `publishConfig` to each field that points at your sources. pnpm applies it to all of them. Yarn 4 applies it to every field but `typesVersions`, Yarn 3 to `exports`, `imports`, `main`, and `module`, and Yarn 2 to `main` and `module`. npm, Yarn 1, and bun pack `package.json` as written. -- `publishConfig` has to set each of those fields, to paths that pass the checks above. +The build reads the package manager from the `npm_config_user_agent` and `npm_execpath` environment variables. It reads the script name from `npm_lifecycle_event`. -The build reads the package manager from the `npm_config_user_agent` and `npm_execpath` environment variables, and the script from `npm_lifecycle_event`. A `prepack` script that runs another script, such as `"prepack": "npm run build"`, isn't checked, because the nested script runs as `build`. Run `tsdown` or `nuxt-module-build build` from `prepack` directly. With source exports, a `release` script that runs `npm publish` fails, even when `pnpm run` starts it. `npm publish` of a tarball that `pnpm pack` wrote works, as its `package.json` already has the `dist` paths and the build doesn't run again. +A `prepack` script that runs another script, such as `"prepack": "npm run build"`, isn't checked, because the nested script runs as `build`. Run `tsdown` or `nuxt-module-build build` from `prepack` directly. After the build, a warning lists the paths in `package.json` that the build didn't produce. diff --git a/docs/4.configuration.md b/docs/4.configuration.md index da591012..e748c809 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -3,7 +3,7 @@ title: Configuration description: Configure the build with `builder()` in `tsdown.config.ts`, build entries other than `src/module.ts`, and keep packages external. --- -The build is configured in a `tsdown.config.ts` in the module root, with the `builder()` plugin from `@nuxt/module-builder/tsdown`. A module with `src/module.ts` and `src/runtime/` needs no options: +You configure the build in a `tsdown.config.ts` in the module root, with the `builder()` plugin from `@nuxt/module-builder/tsdown`. A module with `src/module.ts` and `src/runtime/` needs no options: ```ts [tsdown.config.ts] import { builder } from '@nuxt/module-builder/tsdown' @@ -14,12 +14,20 @@ export default defineConfig({ }) ``` -`tsdown` builds the module with this config, and so does `nuxt-module-build build`. See [Commands](/docs/guide/modules/module-builder/commands). The config is module code, so its relative imports carry their extension, as described in [Module code](/docs/guide/modules/module-builder/typescript#module-code). +Both `tsdown` and `nuxt-module-build build` build the module with this config. See [Commands](/docs/guide/modules/module-builder/commands). + +The config is module code, so its relative imports carry their extension. [Module code](/docs/guide/modules/module-builder/typescript#module-code) describes the rules. ## `builder()` options `builder()` takes three options: +| Option | Description | +|---|---| +| `entries` | Files to build besides `src/module.ts`. See [Bundled entries](#bundled-entries) and [Directory entries](#directory-entries). | +| `externals` | Imports that are never bundled. See [Externals](#externals). | +| `replace` | Compile-time replacements in the bundled entries. See [Replacements](#replacements). | + ```ts [tsdown.config.ts] import { builder } from '@nuxt/module-builder/tsdown' import { defineConfig } from 'tsdown' @@ -39,83 +47,149 @@ export default defineConfig({ }) ``` -- `entries`: files to build besides `src/module.ts`. An entry is either bundled, like `src/module.ts`, or a directory transpiled file by file, like `src/runtime/`. See [Bundled entries](#bundled-entries) and [Directory entries](#directory-entries). -- `externals`: imports that are never bundled. See [Externals](#externals). -- `replace`: compile-time replacements in the bundled entries, as `{ search: replacement }`, or as `{ values, delimiters, preventAssignment, objectGuards }`. - ## Bundled entries -A string, or an object with `input` and an optional `name`, is bundled with tsdown into a single file: +An entry is either bundled into one file, like `src/module.ts`, or transpiled file by file, like `src/runtime/`. A string, or an object with `input` and an optional `name`, is a bundled entry: | Option | Description | |---|---| -| `input` | The entry file, relative to the module root. The extension can be left out. | +| `input` | The entry file, relative to the module root. You can leave out the extension. | | `name` | The output name. Defaults to `input` without `src/` and without its extension. | -Each bundled entry is written to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries). +The build writes each bundled entry to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries in the example above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/guide/modules/module-builder/exports#bundled-entries). -Relative imports in a bundled entry carry the imported file's extension, as in module code, because [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports) point at the entry as it is. - -## Externals - -Bundled entries share the module entry's externals. These are never bundled: - -- `@nuxt/kit`, `@nuxt/schema`, `nuxt`, `vue`, and the `#app`, `#build`, and `#imports` aliases. -- Your module's own package name. -- `dependencies`, `peerDependencies`, and `optionalDependencies`. -- The imports in `builder({ externals })`. +Relative imports in a bundled entry carry the imported file's extension, as in module code. [Source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports) point at the entry as it is, so the entry has to load as written: -Any other import is bundled into the entry that imports it, such as a `devDependency`, or a `#` subpath import from the `imports` field of `package.json`. +```ts [src/utils.ts] +import { normalizeOptions } from './options.ts' -To keep a package that isn't a dependency out of the bundled entries, list it in `externals`. Each name also covers its subpaths, so `shiki` keeps `shiki/core` external too. A regular expression matches the import as written. The import is then kept as written, and resolves in the app that installs the module. tsdown's `deps.neverBundle` adds to the same list. +export function defineMyModuleOptions(options: Record) { + return normalizeOptions(options) +} +``` ## Directory entries -An object whose `input` ends in `/` is a directory. Every file in it is transpiled on its own, in the same way as `src/runtime/`: +An object whose `input` ends in `/` is a directory entry. The build transpiles every file in it on its own, in the same way as `src/runtime/`: | Option | Description | |---|---| | `input` | The source directory, relative to the module root, ending in `/`. | -| `outDir` | The output directory. Defaults to `dist`. It must be inside `dist`. | +| `outDir` | The output directory. Defaults to `dist`, and must be inside `dist`. | | `ext` | The extension of emitted scripts: `mjs` (the default) or `js`. Declarations use the matching `.d.mts` or `.d.ts`. | -The entry above writes the files of `src/features/` to `dist/features/`, with `.js` scripts and `.d.ts` declarations. See [Build output](/docs/guide/modules/module-builder/output#runtime-files) for how each kind of file is emitted. +The entry in the example above writes the files of `src/features/` to `dist/features/`, with `.js` scripts and `.d.ts` declarations. [Build Output](/docs/guide/modules/module-builder/output#runtime-files) describes how each kind of file is emitted. + +Files in a directory entry follow the rules of the runtime directory. Their relative imports can leave out the extension, unless module code imports them by value. Module code that imports them points at their output, instead of bundling them. + +## Externals + +Bundled entries share the module entry's externals. The build never bundles these imports: + +- `@nuxt/kit`, `@nuxt/schema`, `nuxt`, and `vue`. +- The `#app`, `#build`, and `#imports` aliases. +- Your module's own package name. +- The packages in `dependencies`, `peerDependencies`, and `optionalDependencies`. +- The imports in `builder({ externals })` and in tsdown's `deps.neverBundle`. + +The build bundles any other import into the entry that imports it. That includes a `devDependency`, and a `#` subpath import from the `imports` field of `package.json`. -Files in a directory entry follow the rules of the runtime directory. Their relative imports can leave out the extension, unless module code imports them by value. Module code that imports them points at their output instead of bundling them. +To keep a package that isn't a dependency out of the bundled entries, add it to `externals`. A string also covers the package's subpaths, so `shiki` keeps `shiki/core` external too. A regular expression matches the import as written: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [ + builder({ + externals: ['shiki', /^@shikijs\//], + }), + ], +}) +``` + +The build keeps an external import as written, and the import resolves in the app that installs the module. + +## Replacements + +`replace` replaces strings in the bundled entries at build time. Pass an object of search strings and their replacements: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [ + builder({ + replace: { __VERSION__: JSON.stringify('1.0.0') }, + }), + ], +}) +``` + +To set more options, pass `{ values, delimiters, preventAssignment, objectGuards }` instead. These options follow rolldown's replace plugin. ## tsdown options -Other tsdown options apply as usual, such as `outDir` (inside the module), `sourcemap`, `define`, `report`, `plugins`, and `hooks`. `--outDir` and `--sourcemap` on the command line take precedence over the config. +Other tsdown options apply as usual, such as `outDir`, `sourcemap`, `define`, `report`, `plugins`, and `hooks`. The output directory must be inside the module. `--outDir` and `--sourcemap` on the command line take precedence over the config: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + outDir: 'build', + sourcemap: true, + plugins: [builder()], +}) +``` + +### Options that `builder()` sets `builder()` sets these options itself, so the build fails when the config sets them too: - `entry`: list entries in `builder({ entries })` instead. - `format`, other than `esm`. -- `dts`, other than `true`. Declarations are generated with the module's own tsconfig, see [TypeScript](/docs/guide/modules/module-builder/typescript#declarations). -- `clean`: the output directory is emptied before a one-off build, and a watched build removes the files it no longer emits. +- `dts`, other than `true`. Declarations are generated with the module's own tsconfig. See [TypeScript](/docs/guide/modules/module-builder/typescript#declarations). +- `clean`: the build empties the output directory before a one-off build. A watched build removes the files that it doesn't emit any more. - `unbundle`, `exports`, `fixedExtension: false`, `outExtensions`, `platform` other than `node`, and `workspace`. - `external` and `noExternal`: use `builder({ externals })`, `deps.neverBundle`, or `deps.alwaysBundle` instead. -- `deps.neverBundle` set to `true` or a function: list the imports instead. +- `deps.neverBundle` set to `true` or to a function: list the imports instead. -The build also fails when another plugin changes one of these options, or when `outputOptions.entryFileNames` changes the file names of the bundled entries. +The build also fails when another plugin changes one of these options. It fails when `outputOptions.entryFileNames` changes the file names of the bundled entries, too. ### Hooks -`builder()` has no hooks of its own, and fails when it's given `hooks`. Use tsdown's `hooks` in the config, which receive tsdown's context. `ctx.options.cwd` is the module root, and `ctx.options.outDir` the output directory: +`builder()` has no hooks of its own, and fails when you pass it `hooks`. Use tsdown's `hooks` in the config instead. They receive tsdown's context, where `ctx.options.cwd` is the module root and `ctx.options.outDir` is the output directory: -- `build:prepare` runs before `builder()` checks the module's imports and empties the output directory, so it can generate sources. Files written into the output directory there are removed. -- `build:done` runs once the build is complete, after `module.json` and `types.d.mts` are written and the paths in `package.json` are checked. - -To add a file to the output, emit it from a plugin. It's written before the paths in `package.json` are checked: +- `build:prepare` runs before `builder()` checks the module's imports and empties the output directory. Use it to generate sources. The build removes files that this hook writes into the output directory. +- `build:done` runs once the build is complete. By then, `module.json` and `types.d.mts` are written, and the paths in `package.json` are checked. ```ts [tsdown.config.ts] import { builder } from '@nuxt/module-builder/tsdown' import { defineConfig } from 'tsdown' +import { generateTypes } from './scripts/generate-types.ts' export default defineConfig({ hooks: { 'build:prepare': ctx => generateTypes(ctx.options.cwd), }, + plugins: [builder()], +}) +``` + +tsdown's hooks and plugins don't run for `nuxt-module-build prepare`, or for a playground that loads the module from its sources. If `src/module.ts` imports generated sources, commit them. You can also generate them in the module's `dev:prepare` script, before `nuxt-module-build prepare`. + +### Extra files in the output + +To add a file to the output, emit it from a plugin. The build writes it before it checks the paths in `package.json`: + +```ts [tsdown.config.ts] +import { builder } from '@nuxt/module-builder/tsdown' +import { defineConfig } from 'tsdown' + +export default defineConfig({ plugins: [ builder(), { @@ -128,11 +202,9 @@ export default defineConfig({ }) ``` -tsdown's hooks and plugins don't run for `nuxt-module-build prepare`, or for a playground that loads the module from its sources. Commit generated sources that `src/module.ts` imports, or generate them in the module's `dev:prepare` script before `nuxt-module-build prepare`. - ### Other builds in the same config -To build other entries alongside the module, export an array of configs. Give each config its own `outDir`, because the module's output directory is emptied before the build. Call `builder()` once, in the config that builds the module: +To build other entries alongside the module, export an array of configs. Call `builder()` once, in the config that builds the module. Give each config its own `outDir`, because the build empties the module's output directory first: ```ts [tsdown.config.ts] import { builder } from '@nuxt/module-builder/tsdown' @@ -146,7 +218,7 @@ export default defineConfig([ ## Without a tsdown config -Without a `tsdown.config.ts`, `nuxt-module-build build` builds `src/module.ts` and `src/runtime/` on its own, and reads build options such as `entries` and `externals` from the `build` field of `package.json`: +Without a `tsdown.config.ts`, `nuxt-module-build build` builds `src/module.ts` and `src/runtime/` on its own. It reads build options, such as `entries` and `externals`, from the `build` field of `package.json`: ```json [package.json] { @@ -157,11 +229,13 @@ Without a `tsdown.config.ts`, `nuxt-module-build build` builds `src/module.ts` a } ``` -Entries take the same shapes as in `builder({ entries })`. `tsdown` needs the config to build the module, so a module that builds with `tsdown` moves these options into `builder()`. With a tsdown config, a `build` field fails the build. +Entries take the same shapes as in `builder({ entries })`. + +`tsdown` needs the config to build the module. To build with `tsdown`, move these options into `builder()` and remove the field. With a tsdown config, a `build` field fails the build. ## `build.config.ts` -`build.config.ts` (or `.mts`, `.js`, `.mjs`) and the `unbuild` field of `package.json` are deprecated. Without a tsdown config, the build reads them, warns, and still applies these options: +`build.config.ts` (or `.mts`, `.js`, or `.mjs`) and the `unbuild` field of `package.json` are deprecated. Without a tsdown config, the build reads them, prints a warning, and applies these options: - `entries`, in the shapes described above. - `externals`: package names and regular expressions. @@ -169,6 +243,6 @@ Entries take the same shapes as in `builder({ entries })`. `tsdown` needs the co - `sourcemap`: `true` emits source maps, like `--sourcemap`. - The `build:before`, `rollup:done`, and `build:done` hooks. -`mkdist:*` hooks are ignored with a warning, and a few other options are accepted at their defaults. Any other option fails the build, with a list of each one and the file it comes from. With a tsdown config, `build.config.ts` and the `unbuild` field fail the build. +The build ignores `mkdist:*` hooks with a warning, and accepts a few other options at their defaults. Any other option fails the build, with a list of each option and the file that it comes from. With a tsdown config, `build.config.ts` and the `unbuild` field fail the build. -Move their options into `builder()` and tsdown's own `hooks`, then delete the file or remove the field. See [Moving from build.config.ts](/docs/guide/modules/module-builder/upgrade-v2#moving-from-buildconfigts) in the upgrade guide for how each option maps. +Move their options into `builder()` and tsdown's own `hooks`. Then delete the file, or remove the field. [Moving from build.config.ts](/docs/guide/modules/module-builder/upgrade-v2#moving-from-buildconfigts) in the upgrade guide shows how each option maps. diff --git a/docs/5.typescript.md b/docs/5.typescript.md index 6669da98..7596e750 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -1,30 +1,127 @@ --- title: TypeScript -description: Set up the module's `tsconfig.json`, and generate correct declarations for `dist`. +description: Set up the module's `tsconfig.json`, write module code that loads with Node, and generate correct declarations for `dist`. --- -A module has two TypeScript setups: one for the module itself, and one for its playground. This page covers both, and how the build generates the declarations in `dist` from the first. +A module has two TypeScript setups: one for the module itself, and one for its playground. This page covers both. It also describes the rules for module code, and how the build generates the declarations in `dist`. ## The module's `tsconfig.json` -The module root has a `tsconfig.json` of its own, which extends the `.nuxt/tsconfig.json` that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) generates there: +The module root has a `tsconfig.json` of its own. It extends the `.nuxt/tsconfig.json` that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) generates there: ```json [tsconfig.json] { "extends": "./.nuxt/tsconfig.json", + "compilerOptions": { + "erasableSyntaxOnly": true + }, "exclude": ["dist", "node_modules", "playground"] } ``` -This single tsconfig covers `src/module.ts` and `src/runtime/` alike. Your editor, your type check, and the declarations that the build generates all read it, so they see the same types. +This tsconfig covers both `src/module.ts` and `src/runtime/`. Your editor, your type check, and the declarations that the build generates all read it, so they see the same types. + +The `.nuxt` in the module root types the module as Nuxt sees it when the module is installed alone. It uses the module's default options, and disables auto-imports. It's separate from the playground's `.nuxt`, which reflects the playground's configuration and any other modules that it installs. + +- `erasableSyntaxOnly` makes the type check report the syntax that Node can't run in [module code](#module-code). +- `exclude` leaves out `playground`, so the playground's own tsconfig types its files. Add any other directory that isn't part of the module, such as `docs`. + +The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension type-check without further settings. + +## Module code + +`nuxt-module-build prepare` and the build load your module's build-time code with Node, as it is. Module code means these files: + +- `src/module.ts`. +- Every file that `src/module.ts` imports by value, including runtime files. +- `tsdown.config.ts`. + +Node strips types and resolves imports as written. Module code therefore follows the rules in the following sections. `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and every piece of syntax that breaks them. Each entry has its file, line, column, and fix. Until the list is empty, `prepare` doesn't generate `.nuxt`. + +### Relative imports carry their extension + +Write the imported file's extension in every relative import: `./utils.ts`, not `./utils`, `./utils.js`, or `./utils/`: + +```ts [src/module.ts] +import { resolveOptions } from './options.ts' +import { registerComponents } from './components/index.ts' +``` + +Type-only imports don't stop the module from loading, because Node never loads them. Write their extensions too. A type check that resolves imports like Node requires them, such as the playground's check of its `nuxt.config.ts` context when the playground sets `future.compatibilityVersion: 5`. -The `.nuxt` in the module root types the module as Nuxt sees it with the module installed alone, at its default options, with auto-imports disabled. It's separate from the playground's `.nuxt`, which reflects the playground's configuration and any other modules it installs. +Relative imports in other [bundled entries](/docs/guide/modules/module-builder/configuration#bundled-entries) carry their extension as well. Runtime files that module code doesn't import by value can leave out the extension, because the build adds it to their output. -Exclude `playground` so the playground's files are typed by its own tsconfig. Add any other directory that isn't part of the module, such as `docs`, to `exclude` too. +### Only syntax that type stripping removes + +Node removes type annotations, but not TypeScript syntax that generates code. Module code doesn't use `enum`, `namespace` with values, parameter properties, `value` assertions, `import x = require()`, `export =`, or decorators. Rewrite an `enum` as an object and a union type: + +```ts [src/options.ts] +export const Theme = { Light: 'light', Dark: 'dark' } as const +export type Theme = typeof Theme[keyof typeof Theme] +``` + +### No tsconfig `paths` aliases + +Node doesn't read tsconfig `paths`. Use a relative import, or an entry in the `imports` field of `package.json`, which Node resolves itself and the build bundles: + +```json [package.json] +{ + "imports": { + "#internal/*": "./src/internal/*.ts" + } +} +``` + +```ts [src/module.ts] +import { logger } from '#internal/logger' +``` + +### No values from components or JSX + +Node can't load `.vue`, `.tsx`, or `.jsx` files. Move a value that the module needs into a `.ts` file, and import it from there. + +### JSON with an import attribute + +Import JSON with an import attribute, and read properties from its default export: + +```ts [src/module.ts] +import pkg from '../package.json' with { type: 'json' } + +console.log(pkg.version) +``` + +`module.mjs` then contains only the properties that the module reads. Destructuring the import bundles the whole file. + +### No values from `#app`, `#imports`, or `#build` + +`#app`, `#imports`, and `#build/*` only exist inside a Nuxt app. Import types from them, and move the code that needs their values into a runtime file that the module adds, such as a plugin: + +```ts [src/module.ts] +import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addPlugin(resolver.resolve('./runtime/app/plugins/setup')) + }, +}) +``` + +```ts [src/runtime/app/plugins/setup.ts] +import { defineNuxtPlugin } from '#imports' + +export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.hook('app:mounted', () => { + console.log('my-module is ready') + }) +}) +``` ## The playground's `tsconfig.json` -The playground is a Nuxt app, so its `tsconfig.json` is set up like any other Nuxt app's, against the `.nuxt` that `nuxt prepare playground` generates. The starter uses: +The playground is a Nuxt app, so you set up its `tsconfig.json` like any other Nuxt app's. It uses the `.nuxt` that `nuxt prepare playground` generates: ```json [playground/tsconfig.json] { @@ -32,8 +129,6 @@ The playground is a Nuxt app, so its `tsconfig.json` is set up like any other Nu } ``` -A playground can also use the project references that Nuxt generates for an app. See [TypeScript](/docs/guide/concepts/typescript) in the Nuxt docs. - To type-check the module and the playground, run the type check once in each: ```json [package.json] @@ -44,39 +139,44 @@ To type-check the module and the playground, run the type check once in each: } ``` +A playground can also use the project references that Nuxt generates for an app, in a `tsconfig.json` with `"files": []` and `references`. Type-check it with `vue-tsc -b --noEmit`, because `vue-tsc --noEmit` checks no files in that tsconfig. See [TypeScript](/docs/guide/concepts/typescript) in the Nuxt docs. + ### With source exports -With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the playground resolves the module to your sources. Its type check then includes `src/module.ts`, the runtime files, and the files they import types from, checked with the playground's compiler options. The root export's `types` condition points at `.nuxt/module-builder/types.d.mts`, so the playground sees the module's [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets). +With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the playground resolves the module to your sources. Its type check then includes `src/module.ts`, the runtime files, and the files that they import types from. It checks them with the playground's compiler options. + +The root export's `types` condition points at `.nuxt/module-builder/types.d.mts`, so the playground sees the module's [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets). -The errors this can report, and their fixes: +The type check can report these errors: -- `#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context, through types that module code imports from a runtime file that uses them: move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. -- Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context, which resolves imports like Node when the playground sets `future.compatibilityVersion: 5`: add extensions to type-only relative imports as well. -- Globals that the module declares in its own `.d.ts` not found (TS2304), because the playground doesn't include that file: reference it with `/// ` from the files that use the globals. -- The module's own aliases not found (TS2307): move an alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`. TypeScript resolves those from the module's files in any project. Declare the types of an alias that the module adds itself, such as a virtual module, with `addTypeTemplate(template, { nuxt: true, node: true })`, so both of the playground's contexts include them. -- Other errors in runtime files: fix them, or check the module with the same compiler options. +- **`#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context.** Module code imports types from a runtime file that uses these aliases. Move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. +- **Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context.** This context resolves imports like Node when the playground sets `future.compatibilityVersion: 5`. Add extensions to type-only relative imports as well. +- **Globals that the module declares in its own `.d.ts` not found (TS2304).** The playground doesn't include that file. Reference it with `/// ` from the files that use the globals. +- **The module's own aliases not found (TS2307).** Move each alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`. TypeScript resolves those from the module's files in any project. +- **A virtual module that the module adds not found (TS2307).** Declare its types with `addTypeTemplate(template, { nuxt: true, node: true })` from `@nuxt/kit`, so both of the playground's contexts include them. +- **Other errors in runtime files.** Fix them, or check the module with the same compiler options as the playground. ## Monorepos -In a monorepo, give the module its own `tsconfig.json` as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Move any `compilerOptions` the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check and to its declarations. +In a monorepo, give the module its own `tsconfig.json`, as shown above. Don't rely on a root tsconfig or on an app's `.nuxt` for it. Move any `compilerOptions` that the module relies on into it, such as `"types": ["youtube"]` for a global namespace. They then apply to the module's own type check and to its declarations. -The tsconfig that covers your module might extend or reference another app's `.nuxt/tsconfig.json` instead. In that case, the build generates declarations with the module's `./.nuxt/tsconfig.json` plus that tsconfig's own `compilerOptions`, and prints a note. See [Module tsconfig](/docs/guide/modules/module-builder/upgrade-v2#module-tsconfig) in the upgrade guide. +The tsconfig that covers your module might extend or reference another app's `.nuxt/tsconfig.json` instead. In that case, the build generates declarations with the module's `./.nuxt/tsconfig.json`, plus that tsconfig's own `compilerOptions`, and prints a note. See [Module tsconfig](/docs/guide/modules/module-builder/upgrade-v2#module-tsconfig) in the upgrade guide. ## Declarations The build generates declarations from your module's own files, with the module's tsconfig: -- The module entry and every other bundled entry, with TypeScript, or with oxc when `isolatedDeclarations` is set. -- Every script in the runtime directory and other directory entries, with TypeScript. +- The module entry and every other bundled entry, with TypeScript. With `isolatedDeclarations`, it uses oxc instead. +- 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 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. Files that your module's sources import are still followed, wherever they are. +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. ### Errors that fail the build -An error that leaves a declaration missing or wrong fails the build. The most common is an export whose inferred type refers to a package your module can't import by name (TS2742, TS2883, or TS4023). Give each export it lists an explicit type annotation. In this example, the handler's arguments are omitted: +An error that leaves a declaration missing or wrong fails the build. The most common one is an export whose inferred type refers to a package that your module can't import by name (TS2742, TS2883, or TS4023). Give each export that the error lists an explicit type annotation. In this partial example, the handler's arguments are left out: ```ts // before @@ -90,13 +190,13 @@ Syntax errors, and files for which no declaration can be emitted, fail the build ### Type errors reported as warnings -Every other type error, such as a wrong argument type, is reported as a warning. The build prints one warning per directory, with the number of errors and the first three. Run your module's own type check to see them all. +The build reports every other type error, such as a wrong argument type, as a warning. It prints one warning per directory, with the number of errors and the first three. Run your module's own type check to see them all. -Build-time aliases (`#build/*`, `#internal/*`, and other paths into `.nuxt`) are typed as `any` while declarations are generated. So are they in `dist`: an export whose type is inferred through one of them is declared as `any`. Annotate such an export with a type that refers to it by name. The type then resolves against the `.nuxt` of the app that installs the module. See [Other type errors](/docs/guide/modules/module-builder/upgrade-v2#other-type-errors) in the upgrade guide. +Build-time aliases, such as `#build/*`, `#internal/*`, and other paths into `.nuxt`, are typed as `any` while declarations are generated. They're `any` in `dist` too, so an export whose type is inferred through one of them is declared as `any`. Annotate such an export with a type that refers to the alias by name. The type then resolves against the `.nuxt` of the app that installs the module. See [Other type errors](/docs/guide/modules/module-builder/upgrade-v2#other-type-errors) in the upgrade guide. ### `isolatedDeclarations` -With `isolatedDeclarations: true` in the module's tsconfig, the module entry's declarations come from oxc. Every export then needs an explicit type, including the module definition: +With `isolatedDeclarations: true` in the module's tsconfig, the module entry's declarations come from oxc. oxc is faster than TypeScript, but every export then needs an explicit type, including the module definition: ```ts [src/module.ts] import { defineNuxtModule } from '@nuxt/kit' @@ -108,6 +208,7 @@ export interface ModuleOptions { const module: NuxtModule = defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' }, + defaults: { apiKey: '' }, setup() {}, }) @@ -115,32 +216,3 @@ export default module ``` Without `isolatedDeclarations`, the build prints a reminder once per run outside CI. Both settings work. - -## Module code - -`nuxt-module-build prepare` and the build load the module's build-time code with Node, as it is. Module code is `src/module.ts`, every file it imports by value (runtime files included), and `tsdown.config.ts`. Node strips types and resolves imports as written, so module code follows these rules: - -- Relative imports carry the imported file's extension: `./utils.ts`, not `./utils`, `./utils.js`, or `./dir`. -- TypeScript syntax that stripping types doesn't remove isn't used: `enum`, `namespace` with values, parameter properties, `value` assertions, `import x = require()`, `export =`, and decorators. -- Imports don't go through tsconfig `paths` aliases. Use a relative import, or an entry in the `imports` of `package.json`, which Node resolves itself and the build bundles. -- Values aren't imported from `.vue`, `.tsx`, or `.jsx` files. Move a value the module needs into a `.ts` file. -- JSON is imported with an import attribute, as `import pkg from '../package.json' with { type: 'json' }`. Read properties from it rather than destructuring it, so `module.mjs` only contains the properties that are read. -- Values aren't imported from `#app`, `#imports`, or `#build/*`, which only exist inside a Nuxt app. Move the code that needs them into a runtime file the module adds, such as a plugin. - -`prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and piece of syntax that breaks these rules, each with its file, line, column, and fix. Until the list is empty, `prepare` doesn't generate `.nuxt`. - -Type-only imports don't stop the module from loading, as Node never loads them. Write their extensions too: a type check that resolves imports like Node requires them, such as the playground's check of its `nuxt.config.ts` context when the playground sets `future.compatibilityVersion: 5`. Relative imports in other [bundled entries](/docs/guide/modules/module-builder/configuration#bundled-entries) carry their extension as well. Runtime files that module code doesn't import by value keep extensionless imports, as the build adds the extension to their output. - -`erasableSyntaxOnly` makes the type check report the syntax that Node's type stripping can't run: - -```json [tsconfig.json] -{ - "extends": "./.nuxt/tsconfig.json", - "compilerOptions": { - "erasableSyntaxOnly": true - }, - "exclude": ["dist", "node_modules", "playground"] -} -``` - -The generated `.nuxt/tsconfig.json` sets `allowImportingTsExtensions`, so relative imports with a `.ts` extension type-check without further settings. diff --git a/docs/6.output.md b/docs/6.output.md index 9ef5f736..8f6e0d50 100644 --- a/docs/6.output.md +++ b/docs/6.output.md @@ -3,7 +3,7 @@ title: Build Output description: The files that the build writes to `dist`, and the size report it prints. --- -A module with `src/module.ts`, `src/runtime/`, and a `./src/utils` [entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into: +This page describes each file that the build writes to `dist`, and the size report that it prints. A module with `src/module.ts`, `src/runtime/`, and a `./src/utils` [entry](/docs/guide/modules/module-builder/configuration#bundled-entries) builds into this layout: ```bash dist/ @@ -20,18 +20,21 @@ The output is ES modules only. Set `sourcemap` in `tsdown.config.ts`, or pass `- ## `module.mjs` -`src/module.ts`, bundled with tsdown. It's compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. +`module.mjs` is `src/module.ts`, bundled with tsdown. It's compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. -Imports of the runtime directory, and of other directory entries, point at their output in `dist` and aren't bundled. See [Configuration](/docs/guide/modules/module-builder/configuration#bundled-entries) for the packages that stay external. +Imports of the runtime directory, and of other directory entries, point at their output in `dist`. The build doesn't bundle them. See [Configuration](/docs/guide/modules/module-builder/configuration#bundled-entries) for the packages that stay external. ## `module.json` -The module's meta. It contains the `meta` of the module definition, and the versions of `@nuxt/module-builder` and `tsdown` that built it. When the definition doesn't set `name` or `version`, they come from `package.json`. The build loads `dist/module.mjs` to read it. +`module.json` holds the module's meta. It contains the `meta` of the module definition, and the versions of `@nuxt/module-builder` and `tsdown` that built it. When the definition doesn't set `name` or `version`, they come from `package.json`. The build loads `dist/module.mjs` to read the meta. ```json [dist/module.json] { "name": "my-module", "configKey": "myModule", + "compatibility": { + "nuxt": ">=4.0.0" + }, "version": "1.0.0", "builder": { "@nuxt/module-builder": "2.0.0", @@ -42,7 +45,7 @@ The module's meta. It contains the `meta` of the module definition, and the vers ## `types.d.mts` -The types of the package's root export. It re-exports the value exports of `module.d.mts`, including its default export, and re-exports its type-only exports as types. It also adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: +`types.d.mts` holds the types of the package's root export. It re-exports the value exports of `module.d.mts`, including its default export. It re-exports the type-only exports of `module.d.mts` as types. It also adds the [type exports](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` to Nuxt's own types: ```ts [dist/types.d.mts] import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs' @@ -62,11 +65,11 @@ export { type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, t When `src/module.ts` doesn't export `ModuleOptions`, `types.d.mts` infers it from the default export. -[`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes the same augmentations for your sources to `.nuxt/module-builder/types.d.mts`, which re-exports `src/module.ts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it while you develop. +[`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes the same augmentations for your sources to `.nuxt/module-builder/types.d.mts`. That file re-exports `src/module.ts`. With [source exports](/docs/guide/modules/module-builder/develop-and-publish#source-exports), the root export's `types` condition points at it while you develop. ## Runtime files -Every file under `src/runtime/` is emitted under `dist/runtime/` with its name intact, apart from the extension: +The build emits every file under `src/runtime/` under `dist/runtime/`. It keeps each file's name, apart from the extension: | Source | Output | |---|---| @@ -85,15 +88,33 @@ Scripts are transpiled with oxc, one file at a time. Each keeps its own imports - Non-relative imports (`#imports`, `#build/*`, and packages) are kept as written. - Imports used only as types are removed. -A relative import of a file outside `src/runtime/` emits that file too, where the import points: `src/shared/x.ts` becomes `dist/shared/x.js`. When that would leave `dist` or take the name of another output, it's emitted under `dist/_external/` instead. A file that is only imported for its types gets a declaration and no script. +A relative import of a file outside `src/runtime/` emits that file too, where the import points. For example, `src/shared/format.ts` becomes `dist/shared/format.js`. When that path would leave `dist`, or take the name of another output, the file goes under `dist/_external/` instead. A file that is only imported for its types gets a declaration and no script. -`.css` `@import` statements are kept as written. Postcss configuration isn't applied to runtime stylesheets; process them in the Nuxt app, or before the build. +`.css` `@import` statements are kept as written. The build doesn't apply postcss configuration to runtime stylesheets. Process them in the Nuxt app, or before the build. -Other [directory entries](/docs/guide/modules/module-builder/configuration#directory-entries) are emitted in the same way, under their own `outDir`, with `.mjs` and `.d.mts` unless their `ext` is `js`. In every directory, a file whose JSX is kept is emitted as `.jsx` with a `.d.ts`. +Other [directory entries](/docs/guide/modules/module-builder/configuration#directory-entries) are emitted in the same way, under their own `outDir`. Their scripts get `.mjs` and `.d.mts`, unless their `ext` is `js`. In every directory, a file whose JSX is kept is emitted as `.jsx` with a `.d.ts`. ### JSX -`.tsx` and `.jsx` files keep their JSX, so the app that installs the module compiles it with its own Vue JSX plugin. Refer to these files without an extension, as in `resolver.resolve('./runtime/app/components/Banner')`. The path then resolves to the `.tsx` source in development and to the `.jsx` output once the module is published. +`.tsx` and `.jsx` files keep their JSX, so the app that installs the module compiles it with its own Vue JSX plugin. Refer to these files without an extension: + +```ts [src/module.ts] +import { addComponent, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addComponent({ + name: 'MyBanner', + filePath: resolver.resolve('./runtime/app/components/Banner'), + }) + }, +}) +``` + +The path then resolves to the `.tsx` source when `package.json` points at your sources, and to the `.jsx` output in `dist`. Nitro and Node don't transform files in `node_modules`. JSX that runs there is compiled to `vue/jsx-runtime` calls instead, and the file is emitted as `.js`. This applies to: @@ -104,7 +125,7 @@ An import through an alias or through the module's own package name isn't follow ## Runtime declarations -Declarations of runtime files are rewritten so they resolve in the app that installs the module: +The build rewrites the declarations of runtime files, so they resolve in the app that installs the module: - Relative imports get the extension of the file they resolve to, for `node16` and `nodenext` module resolution. - `#app` imports become `nuxt/app`. diff --git a/docs/7.exports.md b/docs/7.exports.md index b98ebbf0..517a91b7 100644 --- a/docs/7.exports.md +++ b/docs/7.exports.md @@ -3,7 +3,7 @@ title: Exports description: Publish more entry points than the module itself, such as utilities, composables, and components. --- -The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. Named values and types exported by `src/module.ts` are re-exported from the root too. Anything else you want users to import by name needs its own subpath in the `exports` of `package.json`. +The root export of a module is its definition, `dist/module.mjs`, with `dist/types.d.mts` for its types. The root also re-exports the named values and types that `src/module.ts` exports. Anything else that you want users to import by name needs its own subpath in the `exports` of `package.json`. The examples on this page show the published `exports`, which point at `dist`. With source exports, put them in `publishConfig.exports`, and point each subpath of `exports` at its source. See [Source exports](#source-exports). @@ -26,13 +26,22 @@ A [bundled entry](/docs/guide/modules/module-builder/configuration#bundled-entri } ``` -Users then import it as `my-module/utils`. A bundled entry suits code that runs alongside the module, such as helpers for `nuxt.config` or for other modules. +Users then import it as `my-module/utils`. A bundled entry suits code that runs alongside the module, such as helpers for `nuxt.config` or for other modules: -TypeScript reads the `types` condition of each export with the `bundler` and `node16` module resolution, which Nuxt apps use. `node10` module resolution ignores `exports`, and these docs don't cover it. If your module keeps a top-level `types` field or `typesVersions` for it, see [The types field](/docs/guide/modules/module-builder/upgrade-v2#the-types-field) and [typesVersions paths](/docs/guide/modules/module-builder/upgrade-v2#typesversions-paths) in the upgrade guide. +```ts [nuxt.config.ts] +import { defineMyModuleOptions } from 'my-module/utils' + +export default defineNuxtConfig({ + modules: ['my-module'], + myModule: defineMyModuleOptions({ greeting: 'Hi' }), +}) +``` + +TypeScript reads the `types` condition of each export under the `bundler` and `node16` module resolution, which Nuxt apps use. `node10` module resolution ignores `exports`, and these docs don't cover it. If your module keeps a top-level `types` field or `typesVersions` for it, see [The types field](/docs/guide/modules/module-builder/upgrade-v2#the-types-field) and [typesVersions paths](/docs/guide/modules/module-builder/upgrade-v2#typesversions-paths) in the upgrade guide. ## Runtime files -Files in `src/runtime/` can be exported too, from their output in `dist/runtime/`. This lets an app import them explicitly, as well as through whatever the module registers for auto-import. +You can export files in `src/runtime/` too, from their output in `dist/runtime/`. An app can then import them explicitly, as well as through whatever the module registers for auto-import. To export a set of components, re-export them from an `index.ts` in the same directory: @@ -88,7 +97,42 @@ export default defineNuxtModule({ }) ``` -`` and `` are then available without an import. Composables and utilities work the same way: export them from an index, and register them with `addImports` or `addImportsDir`. +`` and `` are then available without an import. + +Composables work the same way. Export them from a file in the runtime directory, and point a subpath at its output: + +```ts [src/runtime/app/composables/index.ts] +export { useGreeting } from './useGreeting' +``` + +```json [package.json] +{ + "exports": { + "./composables": { + "types": "./dist/runtime/app/composables/index.d.ts", + "import": "./dist/runtime/app/composables/index.js" + } + } +} +``` + +To register them for auto-import, pass each one to `addImports`, or pass their directory to `addImportsDir`: + +```ts [src/module.ts] +import { addImports, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addImports({ + name: 'useGreeting', + from: resolver.resolve('./runtime/app/composables/useGreeting'), + }) + }, +}) +``` ::note With `exports` that point at `dist`, these subpaths resolve once the module has been built. [Source exports](#source-exports) resolve them to your sources while you develop. @@ -127,12 +171,16 @@ With [source exports](/docs/guide/modules/module-builder/develop-and-publish#sou } ``` -- Each subpath of `exports` points at the source file that the build turns into the matching path of `publishConfig.exports`. `publishConfig.exports` replaces `exports` as a whole, so it repeats every subpath. -- The root export's `types` condition points at the declarations that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes, so the [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` apply in the playground. A subpath has no augmentations, so it points at its source alone. -- A subpath that code outside Nuxt imports, such as a plugin for a plain Vite app, can keep pointing at `dist` in `exports`, so that code loads the built file. Build the module before using it. +- Each subpath of `exports` points at the source file that the build turns into the matching path of `publishConfig.exports`. +- `publishConfig.exports` replaces `exports` as a whole, so it repeats every subpath. +- The root export's `types` condition points at the declarations that [`nuxt-module-build prepare`](/docs/guide/modules/module-builder/commands#prepare) writes. The [type augmentations](/docs/guide/modules/module-builder/project-structure#srcmodulets) of `src/module.ts` then apply in the playground. +- A subpath has no augmentations, so it points at its source alone. +- A subpath that code outside Nuxt imports, such as a plugin for a plain Vite app, can keep pointing at `dist` in `exports`. That code then loads the built file. Build the module before you use it. The build checks the paths in `publishConfig.exports`, not the source paths in `exports`. See [Checks on published paths](/docs/guide/modules/module-builder/develop-and-publish#checks-on-published-paths). ## Importing your own exports -Runtime code and module code can import the module's own package name, such as `my-module/utils`. These imports are never bundled, and resolve to the published files in the app that installs the module. While the build generates declarations, they resolve to your sources instead, so they type-check before `dist` exists. With source exports, the subpaths and their `dist` paths are read from `publishConfig.exports`. +Runtime code and module code can import the module's own package name, such as `my-module/utils`. The build never bundles these imports, so they resolve to the published files in the app that installs the module. + +While the build generates declarations, these imports resolve to your sources instead, so they type-check before `dist` exists. With source exports, the build reads the subpaths and their `dist` paths from `publishConfig.exports`. diff --git a/docs/8.transpile-dir.md b/docs/8.transpile-dir.md index 7e5ecbaf..63677bc1 100644 --- a/docs/8.transpile-dir.md +++ b/docs/8.transpile-dir.md @@ -3,7 +3,7 @@ title: Transpiling a Directory description: Use the `transpileDir` rolldown plugin to transpile a directory file by file in any tsdown or rolldown build. --- -The runtime build is a rolldown plugin, `transpileDir`, exported from `@nuxt/module-builder/rolldown`. Use it in any tsdown or rolldown build that transpiles a directory file by file instead of bundling it: +`builder()` transpiles the runtime directory with a rolldown plugin, `transpileDir`, which `@nuxt/module-builder/rolldown` exports. Use it in any tsdown or rolldown build that transpiles a directory file by file instead of bundling it, such as a library that isn't a Nuxt module: ```ts [tsdown.config.ts] import { defineConfig } from 'tsdown' @@ -17,11 +17,16 @@ export default defineConfig({ }) ``` -Every file under `srcDir` is emitted under `outBase` in the build's output directory, with its name intact apart from the extension. Scripts become `.js` (or `.mjs`), `.tsx` and `.jsx` files become `.jsx` while their JSX is preserved, and compiled Sass becomes `.css`. Test and story files are excluded by default. +The plugin emits every file under `srcDir` under `outBase` in the build's output directory. It keeps each file's name, apart from the extension: -Scripts are transpiled with oxc and keep their imports as written, apart from relative imports, which get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. +- Scripts become `.js`, or `.mjs` with `extension: 'mjs'`. +- `.tsx` and `.jsx` files become `.jsx`, with their JSX kept. +- Sass files compile to `.css`. +- Test and story files are left out by default. -By default, scripts are transpiled with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. The `builder()` plugin passes the `transform` of the `rolldown` that `tsdown` installs, so a module that builds with it needs neither. +Scripts are transpiled with oxc, and keep their imports as written. Relative imports are the exception: they get the emitted extension. `.vue` files are transpiled with `vue-sfc-transformer`, stylesheets are processed as described in [Build Output](/docs/guide/modules/module-builder/output#runtime-files), and other files are copied. Declarations come from one TypeScript program that uses the nearest `tsconfig.json`. + +By default, the plugin transpiles scripts with the `transform` from `rolldown/utils`. `rolldown` is an optional peer dependency of `@nuxt/module-builder`, so install it in your project, or pass a `transform` of your own. `builder()` passes the `transform` of the `rolldown` that `tsdown` installs, so a module that builds with `builder()` needs neither. ## Options @@ -47,17 +52,33 @@ The options are documented in full on the `TranspileDirOptions` type. ## Imports outside `srcDir` -By default, a relative import that resolves outside `srcDir` is kept as written. `resolveExternal` is called for each one. Its third argument describes the import: the absolute path of the file, and whether the import is for its value or only its type. It also gives the paths where the importer and the file would be emitted. It returns one of: +By default, the plugin keeps a relative import that resolves outside `srcDir` as written. To change that, pass `resolveExternal`, which the plugin calls for each such import. Its third argument describes the import: + +- `file`: the absolute path of the imported file. +- `kind`: `'value'`, or `'type'` for an import that's only used for its type. +- `from` and `output`: the paths where the importer and the imported file would be emitted. + +`resolveExternal` returns one of these values: - A string: the specifier to write instead. -- `{ mirror: 'value' }` or `{ mirror: 'type' }`: emit the file alongside the directory, as a script and declaration, or as a declaration only. An `output` path, relative to the output directory, overrides where it's emitted. +- `{ mirror: 'value' }` or `{ mirror: 'type' }`: emit the file alongside the directory, as a script and a declaration, or as a declaration only. An `output` path, relative to the output directory, overrides where the file goes. - `undefined`: keep the specifier as written. +This config emits every imported file outside `srcDir` next to the directory: + ```ts [tsdown.config.ts] -transpileDir({ - srcDir: 'src/runtime', - outBase: 'runtime', - resolveExternal: (_specifier, _importer, { kind }) => ({ mirror: kind }), +import { defineConfig } from 'tsdown' +import { transpileDir } from '@nuxt/module-builder/rolldown' + +export default defineConfig({ + entry: ['src/index.ts'], + plugins: [ + transpileDir({ + srcDir: 'src/runtime', + outBase: 'runtime', + resolveExternal: (_specifier, _importer, { kind }) => ({ mirror: kind }), + }), + ], }) ``` @@ -79,4 +100,21 @@ export default defineConfig({ ## Type errors -Errors that would leave a declaration missing or wrong fail the build. Other type errors are reported as one warning per directory. Its `pluginCode` equals the `TYPE_ERRORS_WARNING` constant, exported from `@nuxt/module-builder/rolldown`, so an `onLog` handler can filter the warning or turn it into an error. +Errors that would leave a declaration missing or wrong fail the build. The plugin reports other type errors as one warning per directory. The warning's `pluginCode` equals the `TYPE_ERRORS_WARNING` constant from `@nuxt/module-builder/rolldown`. An `onLog` handler can then filter the warning, or turn it into an error: + +```ts [tsdown.config.ts] +import { defineConfig } from 'tsdown' +import { transpileDir, TYPE_ERRORS_WARNING } from '@nuxt/module-builder/rolldown' + +export default defineConfig({ + entry: ['src/index.ts'], + inputOptions: { + onLog(level, log, handler) { + handler(log.pluginCode === TYPE_ERRORS_WARNING ? 'error' : level, log) + }, + }, + plugins: [ + transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }), + ], +}) +``` diff --git a/docs/cli/build-module/index.md b/docs/cli/build-module/index.md index 91fe3372..0b9f320d 100644 --- a/docs/cli/build-module/index.md +++ b/docs/cli/build-module/index.md @@ -17,7 +17,7 @@ The `build-module` command runs the `nuxt-build-module` binary that [`@nuxt/modu ## `build` -Builds the module into `dist` for publishing, with the module's `tsdown.config.ts` when it has one. It produces the same output as `tsdown`. See [`build`](/docs/guide/modules/module-builder/commands#build). +Builds the module into `dist` for publishing. When the module has a `tsdown.config.ts`, `build` uses it. It produces the same output as `tsdown`. See [`build`](/docs/guide/modules/module-builder/commands#build). ### Arguments @@ -35,7 +35,7 @@ Builds the module into `dist` for publishing, with the module's `tsdown.config.t ## `prepare` -Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends, and the declarations that the root export's `types` condition points at while `package.json` points at the module's sources. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). +Generates `.nuxt` in the module root, which the module's `tsconfig.json` extends. It also writes the declarations that the root export's `types` condition points at while `package.json` points at the module's sources. See [`prepare`](/docs/guide/modules/module-builder/commands#prepare). ### Arguments diff --git a/docs/index.md b/docs/index.md index 91679be9..d5399dba 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,9 +5,9 @@ navigation: title: Getting Started --- -`@nuxt/module-builder` builds a Nuxt module for publishing to npm. Its `builder()` plugin makes [tsdown](https://tsdown.dev) bundle the module entry and transpile the runtime directory file by file. It also generates type declarations against the module's own `.nuxt`, and writes the type shims that give `nuxt.config` autocompletion for the module's options. +`@nuxt/module-builder` builds a Nuxt module for publishing to npm. It provides a [tsdown](https://tsdown.dev) plugin, `builder()`, that bundles your module entry and transpiles your runtime directory file by file. It also generates type declarations against your module's own `.nuxt`, and writes the types that give `nuxt.config` autocompletion for your module's options. -The builder works with the layout of the [module starter](https://github.com/nuxt/starter/tree/module) and needs no options for it. To learn how to write the module itself (its definition, hooks, and the `@nuxt/kit` utilities), read the [Module Author Guide](/docs/guide/modules). +`@nuxt/module-builder` works with the layout of the [module starter](https://github.com/nuxt/starter/tree/module) and needs no options for it. To learn how to write the module itself, such as its definition, its hooks, and the `@nuxt/kit` utilities, read the [Module Author Guide](/docs/guide/modules). ## Requirements @@ -17,10 +17,10 @@ To build a module, you need: - `tsdown` and `typescript` (`^5.9.3 || ^6.0.0`), which are peer dependencies of `@nuxt/module-builder`. - `nuxt`, which provides the `@nuxt/cli` that `nuxt-module-build prepare` runs. -To use a module built with it, an app needs Nuxt 3 or later. The module entry is compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. +An app needs Nuxt 3 or later to use a module that `@nuxt/module-builder` builds. The module entry is compiled for the lowest Node version in your module's `engines.node` field. Without that field, its syntax is kept as written. ::note -Nuxt 3 has reached end of life, so these docs describe Nuxt 4 and later. Where Nuxt 3 behaves differently, such as type-checking all of a module's runtime files in a single context, they don't cover it. +Nuxt 3 has reached end of life, so these docs describe Nuxt 4 and later. They don't cover the places where Nuxt 3 behaves differently, such as type-checking all of a module's runtime files in a single context. :: ## Quick start @@ -55,50 +55,54 @@ npm install npm run dev:prepare ``` -`dev:prepare` generates the `.nuxt` directories that type the module and its playground. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish) for what each step does. +`dev:prepare` generates the `.nuxt` directories that type your module and its playground. To find out what each step does, read [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish). ## Manual installation -Add the builder and its peer dependencies to an existing module: +To add `@nuxt/module-builder` to an existing module, follow these steps: -```bash -pnpm add -D @nuxt/module-builder tsdown@^0.23.7 typescript nuxt -``` +1. Install `@nuxt/module-builder` and its peer dependencies: -Add a `tsdown.config.ts` with the `builder()` plugin: + ```bash + pnpm add -D @nuxt/module-builder tsdown@^0.23.7 typescript nuxt + ``` -```ts [tsdown.config.ts] -import { builder } from '@nuxt/module-builder/tsdown' -import { defineConfig } from 'tsdown' +2. Create a `tsdown.config.ts` in the module root that uses the `builder()` plugin: -export default defineConfig({ - plugins: [builder()], -}) -``` + ```ts [tsdown.config.ts] + import { builder } from '@nuxt/module-builder/tsdown' + import { defineConfig } from 'tsdown' -Then add the scripts that build the module before publishing and prepare it for development: + export default defineConfig({ + plugins: [builder()], + }) + ``` -```json [package.json] -{ - "scripts": { - "prepack": "tsdown", - "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground" - } -} -``` +3. Add the scripts that prepare your module for development and build it before publishing: + + ```json [package.json] + { + "scripts": { + "dev": "nuxt dev playground", + "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground", + "prepack": "tsdown" + } + } + ``` -This `dev:prepare` suits a module that pnpm or Yarn 4 publishes, with `package.json` pointing at its sources. With npm, Yarn 3 or earlier, or bun, add `tsdown` before `nuxt prepare playground`. See [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout). +4. Point the `exports` of `package.json` at your module, as described in [Project Structure](/docs/guide/modules/module-builder/project-structure#packagejson). +5. Create a `tsconfig.json` that extends `.nuxt/tsconfig.json`, as described in [TypeScript](/docs/guide/modules/module-builder/typescript). -Your module also needs the `exports` and `files` fields described in [Project structure](/docs/guide/modules/module-builder/project-structure#packagejson), and a `tsconfig.json` as described in [TypeScript](/docs/guide/modules/module-builder/typescript). +The `dev:prepare` script in step 3 is for a module that you publish with pnpm or Yarn 4. If you publish with npm, Yarn 3 or earlier, or bun, add `tsdown` before `nuxt prepare playground`. [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish#preparing-a-checkout) explains the difference. ## Next steps -- [Project structure](/docs/guide/modules/module-builder/project-structure): the files the builder reads. -- [Commands](/docs/guide/modules/module-builder/commands): `tsdown`, `build`, and `prepare`. -- [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish): the playground, and releasing to npm. -- [Configuration](/docs/guide/modules/module-builder/configuration): `tsdown.config.ts`, extra entries, and directories. -- [TypeScript](/docs/guide/modules/module-builder/typescript): the module's `tsconfig.json` and its declarations. -- [Build output](/docs/guide/modules/module-builder/output): what ends up in `dist`. +- [Project Structure](/docs/guide/modules/module-builder/project-structure): the files that `@nuxt/module-builder` reads. +- [Commands](/docs/guide/modules/module-builder/commands): `tsdown`, `nuxt-module-build build`, and `nuxt-module-build prepare`. +- [Develop and Publish](/docs/guide/modules/module-builder/develop-and-publish): the two development setups, the playground, and releases. +- [Configuration](/docs/guide/modules/module-builder/configuration): `tsdown.config.ts`, extra entries, and externals. +- [TypeScript](/docs/guide/modules/module-builder/typescript): your module's `tsconfig.json`, its declarations, and the rules for module code. +- [Build Output](/docs/guide/modules/module-builder/output): the files in `dist`, and the size report. - [Exports](/docs/guide/modules/module-builder/exports): subpath exports, including runtime components. -- [Transpiling a directory](/docs/guide/modules/module-builder/transpile-dir): the `transpileDir` rolldown plugin. +- [Transpiling a Directory](/docs/guide/modules/module-builder/transpile-dir): the `transpileDir` rolldown plugin. - [Upgrading to v2](/docs/guide/modules/module-builder/upgrade-v2): moving a module from v1. diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index da97ae47..7e9ed561 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -376,7 +376,7 @@ Any other path in `exports`, `main`, `module`, `types`, or `typesVersions` that - With pnpm or Yarn 4, point `package.json` at the module's sources as in [Source exports](#source-exports), and set `"dev:prepare": "nuxt-module-build prepare && nuxt prepare playground"`. - With npm, Yarn 3 or earlier, or bun, keep `package.json` pointing at `dist`, set `"dev:prepare": "nuxt-module-build prepare && tsdown && nuxt prepare playground"`, and run `tsdown --watch` next to `nuxt dev playground`, as in [Developing against dist](#developing-against-dist). -Both scripts start with `nuxt-module-build prepare`, also where the old one had no `prepare` step, such as `nuxt-module-build build --stub . && nuxi prepare playground`. It writes the `.nuxt` that the build reads and, with source exports, the `.nuxt/module-builder/types.d.mts` that `package.json` points at. +Both scripts start with `nuxt-module-build prepare`, also where the old one had no `prepare` step, such as `nuxt-module-build build --stub . && nuxt prepare playground`. It writes the `.nuxt` that the build reads and, with source exports, the `.nuxt/module-builder/types.d.mts` that `package.json` points at. `nuxt-module-build prepare`, and a playground that loads the module from its sources, run `src/module.ts` with Node, so module code follows the rules in [Module code loads with Node](#module-code-loads-with-node). @@ -459,12 +459,29 @@ console.log(pkg.name, pkg.version) `#app`, `#imports`, and `#build/*` only exist inside a Nuxt app. Import types from them, and move code that needs their values into a runtime file the module adds, such as a plugin: ```ts -// before, in src/module.ts +// src/module.ts, before import { useNuxtApp } from '#app' -// after -import type { NuxtApp } from '#app' -addPlugin(resolver.resolve('./runtime/plugin')) +// src/module.ts, after +import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + setup() { + const resolver = createResolver(import.meta.url) + + addPlugin(resolver.resolve('./runtime/plugin')) + }, +}) +``` + +```ts +// src/runtime/plugin.ts +import { defineNuxtPlugin } from '#imports' + +export default defineNuxtPlugin((nuxtApp) => { + // code that needs the Nuxt app +}) ``` Fix the list before you run `prepare` or `dev:prepare`. Until it's empty, `prepare` stops and doesn't generate `.nuxt`. The module's type check and editor types then have nothing to extend. @@ -593,7 +610,7 @@ Each file under `src/runtime` is still emitted under `dist/runtime` with its nam ## Output directory -A one-off build empties `--outDir` (`dist` by default) before writing to it, and `tsdown --watch` removes the files in it that the build no longer emits, so the directory must be inside your module. An `--outDir` of `.`, or of a directory that contains the module, fails the build. +A one-off build empties `--outDir` (`dist` by default) before it writes to it. `tsdown --watch` removes the files in it that the build doesn't emit any more. The directory must therefore be inside your module. An `--outDir` of `.`, or of a directory that contains the module, fails the build. ## Module tsconfig @@ -668,15 +685,24 @@ pnpm and Yarn 4 publish the fields of `publishConfig` in place of the top-level `nuxt-module-build prepare` writes `.nuxt/module-builder/types.d.mts`. It re-exports `src/module.ts` and declares the same `#app` and `@nuxt/schema` augmentations as `dist/types.d.mts`, for the module's `ModuleHooks`, `ModuleRuntimeHooks`, `ModuleRuntimeConfig`, and `ModulePublicRuntimeConfig`. The root export's `types` condition points at it, so the playground's type check sees the module's hooks and runtime config. A module that supports `node10` consumers also sets `publishConfig.types` to `./dist/types.d.mts` (see [The types field](#the-types-field)). A subpath export has no augmentations, so it points at its source. -The playground's type check includes the module's sources and the files they import types from. A built `dist` keeps them out, because declarations aren't checked. The errors this can report, and their fixes: +The playground's type check includes the module's sources and the files that they import types from. A built `dist` keeps them out, because the type check doesn't check declarations. The type check can report these errors: + +- **`#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context.** Module code imports types from a runtime file that uses these aliases. Move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. +- **Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context.** This context resolves imports like Node when the playground sets `future.compatibilityVersion: 5`. Add extensions to type-only relative imports as well. +- **Globals that the module declares in its own `.d.ts` not found (TS2304).** The playground doesn't include that file. Reference it with `/// ` from the files that use the globals. +- **The module's own aliases not found (TS2307).** Move each alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`. TypeScript resolves those from the module's files in any project. +- **A virtual module that the module adds not found (TS2307).** Declare its types with `addTypeTemplate(template, { nuxt: true, node: true })` from `@nuxt/kit`, so both of the playground's contexts include them. +- **Other errors in runtime files.** The playground checks them with its own compiler options. Fix them, or check the module with the same options. -- `#app`, `#imports`, or `#build/*` not found (TS2307, TS2664) in the `nuxt.config.ts` context, through types that module code imports from a runtime file that uses them: move those types into a file that doesn't import the aliases, such as `src/runtime/types.ts`. -- Relative imports without extensions (TS2835, TS2834) in the `nuxt.config.ts` context, which resolves them like Node when the playground sets `future.compatibilityVersion: 5`: add extensions to type-only relative imports as well. -- Globals that the module declares in its own `.d.ts` not found (TS2304), because the playground doesn't include that file: reference it with `/// ` from the files that use the globals. -- The module's own aliases not found (TS2307): move an alias from the module's tsconfig `paths` into the `imports` of `package.json`, with its `dist` paths in `publishConfig.imports`, as TypeScript resolves those from the module's files in any project. Declare the types of an alias that the module adds itself, such as a virtual module, with `addTypeTemplate(template, { nuxt: true, node: true })`, so both of the playground's contexts include them. -- Other errors in runtime files, which are checked with the playground's compiler options: fix them, or check the module with the same options. +With source exports, there is no `dist` while you develop. Code that reaches into `dist` by path has to point at `src`, such as a test that imports `../dist/runtime/...`, or module code that resolves `../dist/runtime/...`. Resolve runtime files relative to `src/module.ts`, without an extension: + +```ts +// src/module.ts +const resolver = createResolver(import.meta.url) +addPlugin(resolver.resolve('./runtime/plugins/plugin')) +``` -With source exports there is no `dist` while you develop, so code that reaches into `dist` by path has to point at `src`: a playground or a test that imports `../dist/runtime/...`, or module code that resolves `../dist/runtime/...`. Resolve runtime files relative to `src/module.ts` and without an extension, as `createResolver(import.meta.url).resolve('./runtime/plugins/plugin')` does: the build keeps the layout of `src` in `dist`, and Nuxt and Vite add the extension. +The build keeps the layout of `src` in `dist`, and Nuxt and Vite add the extension. Build-time code that reads a runtime file's contents, such as code that inlines the file into a template, finds no file at the path without an extension, and TypeScript at the `.ts` path. Generate the template from code that doesn't depend on the built file, or build `dist` first and keep reading from it. @@ -734,7 +760,7 @@ npm, Yarn 3 and earlier, and bun publish some or all of these fields as written. } ``` -A playground that installs the module by name lists it as `"my-module": "workspace:*"` or `"my-module": "link:.."`. npm supports neither protocol, so use `"my-module": "file:.."` there, which npm installs as a link. Yarn 1 has no `workspace:` protocol, so use `link:..` there. +A playground that installs the module by name lists it as `"my-module": "workspace:*"` or `"my-module": "link:.."`. npm supports neither protocol, so use `"my-module": "file:.."` there. npm installs it as a link. Yarn 1 has no `workspace:` protocol, so use `link:..` there. `nuxt-module-build prepare` installs the module from its sources even where its own `.nuxtrc` or `nuxt.config` lists it by name. Any other `nuxt prepare` that loads the module by name, such as one at the repository root with `modules[]=my-module` in `.nuxtrc`, loads it from `dist` and leaves it out when `dist` is missing. Run `tsdown` before such a `nuxt prepare` in `dev:prepare`. @@ -742,7 +768,16 @@ While `nuxt dev playground` runs, run `tsdown --watch` next to it. `tsdown --wat ## Output size -Every tsdown build reports the size of its output. A module with runtime directories gets a summary, followed by one line for each bundled entry and runtime directory, with the size of its code and of its declarations; others get a line for each file. On a rebuild under `tsdown --watch`, the summary and the per-file lines only count the files that were written, while the lines for each entry and runtime directory cover the whole build. Set `report` in `tsdown.config.ts` to change it: `{ summary: true }` or `{ summary: false }`, `{ gzip: false }` to skip compressing each file, `{ brotli: true }`, or `false` to turn it off. `module.json` and `types.d.mts` are written after the report, so they aren't in it. +Every tsdown build reports the size of its output. A module with runtime directories gets a summary, followed by one line for each bundled entry and runtime directory. Each line gives the size of the code and of the declarations. Other modules get a line for each file. + +On a rebuild under `tsdown --watch`, the summary and the lines for each file only count the files that the rebuild wrote. The lines for each entry and runtime directory cover the whole build. `module.json` and `types.d.mts` are written after the report, so they aren't in it. + +Set `report` in `tsdown.config.ts` to change the report: + +- `{ summary: true }` or `{ summary: false }` chooses between the summary and the lines for each file. +- `{ gzip: false }` skips compressing each file. +- `{ brotli: true }` adds the brotli size. +- `false` turns the report off. To check the published size in CI, pack the module with the package manager that publishes it, into a temporary directory. Then list the tarball with `npm pack --dry-run --json`, which gives each file's `size`, plus the gzipped tarball's `size` and the `unpackedSize`. `pnpm pack --json` lists the files without their sizes. @@ -766,16 +801,38 @@ pnpm remove unbuild ## Checklist -Follow these steps in order to upgrade a module. Each step is mechanical until the build runs. Use your module's own package manager where `pnpm` is written. +Follow these steps in order to upgrade a module. Each step is mechanical until the build runs. Where a step says `pnpm`, use your module's own package manager. 1. Use Node 22.18+ or 24+ locally and in CI. -2. Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`, then `pnpm remove unbuild` (and `mkdist` and `jiti`, if they only served the builder). Do this before step 3. -3. Move the options of `build.config.ts` and of the `build` or `unbuild` field of `package.json` into `builder()` in a `tsdown.config.ts`, as described in [Moving from build.config.ts](#moving-from-buildconfigts), including directory entries such as `{ input: 'src/x/', outDir: 'dist/x' }`. Then delete `build.config.ts` and remove the field. A module without options still gets a `tsdown.config.ts` with `plugins: [builder()]`, so that `tsdown` builds it. -4. In `package.json`, replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`, replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. If it does, set `types` to `./dist/types.d.mts` (in `publishConfig` with source exports, see step 8), and give every `typesVersions` path its full file name (`./dist/util.d.mts`, not `dist/util`). -5. Add `"erasableSyntaxOnly": true` to `tsconfig.json`, and rewrite any `enum`, `namespace`, parameter property, or `value` assertion the type check reports. -6. Make module code load with Node, as described in [Module code loads with Node](#module-code-loads-with-node): add the `.ts` extension to relative imports in `src/module.ts` and the files it imports by value, runtime files included (`./utils` becomes `./utils.ts`, `./dir` becomes `./dir/index.ts`), replace value imports through tsconfig `paths` aliases, and move value imports of `#app`, `#imports`, and `#build/*` into runtime files. Do this before step 8: `prepare` lists each problem and doesn't generate `.nuxt` until they're fixed. +2. Install v2 and tsdown, before step 3: + - Run `pnpm add -D @nuxt/module-builder@^2.0.0 tsdown@^0.23.7`. + - Run `pnpm remove unbuild`. Also remove `mkdist` and `jiti`, if they only served the builder. +3. Move the build options into a `tsdown.config.ts`: + - Move the options of `build.config.ts`, and of the `build` or `unbuild` field of `package.json`, into `builder()`. Include directory entries such as `{ input: 'src/x/', outDir: 'dist/x' }`. See [Moving from build.config.ts](#moving-from-buildconfigts). + - Delete `build.config.ts`, and remove the field. + - A module without options still needs a `tsdown.config.ts` with `plugins: [builder()]`, so that `tsdown` builds it. +4. Update the declaration paths in `package.json`: + - Replace `.d.ts` with `.d.mts` for `types.d.ts` and `module.d.ts`. + - Replace `module.cjs` with `module.mjs`, and remove `.cjs` entries. + - Remove the top-level `types` field and `typesVersions`, unless your module supports `node10` consumers. + - If it does, set `types` to `./dist/types.d.mts`, in `publishConfig` with source exports (see step 8). Give every `typesVersions` path its full file name: `./dist/util.d.mts`, not `dist/util`. +5. Add `"erasableSyntaxOnly": true` to `tsconfig.json`. Rewrite any `enum`, `namespace`, parameter property, or `value` assertion that the type check reports. +6. Make module code load with Node, before step 8. `prepare` lists each problem, and doesn't generate `.nuxt` until you fix them all. See [Module code loads with Node](#module-code-loads-with-node): + - Add the `.ts` extension to relative imports in `src/module.ts` and the files that it imports by value, runtime files included. `./utils` becomes `./utils.ts`, and `./dir` becomes `./dir/index.ts`. + - Replace value imports through tsconfig `paths` aliases. + - Move value imports of `#app`, `#imports`, and `#build/*` into runtime files. 7. If the runtime contains `.scss` or `.sass` files, run `pnpm add -D sass`. -8. Set the `prepack` script to `tsdown`. With pnpm or Yarn 4, point `package.json` at the module's sources and the same fields in `publishConfig` at `dist`, and set `dev:prepare` to `nuxt-module-build prepare && nuxt prepare playground`, as in [Source exports](#source-exports). With npm, Yarn 3 or earlier, or bun, set `dev:prepare` to `nuxt-module-build prepare && tsdown && nuxt prepare playground`, as in [Developing against dist](#developing-against-dist). Run `nuxt-module-build prepare`, then `tsdown`. Fix what the build reports: remove each unsupported build option and annotate each export in a portability error. Build again until it passes. -9. Run your module's own type check (for example, `nuxt typecheck` or `vue-tsc --noEmit`) and fix what it reports. A build warning about type errors that the type check doesn't reproduce is safe to ignore. Annotate exports whose type is inferred through a `#build/*` alias; otherwise `dist` declares them as `any`. -10. Run `pnpm dlx publint`. Then run `pnpm pack` and `pnpm dlx @arethetypeswrong/cli -.tgz`, and fix any path they report. (`attw --pack .` only works with npm, and `npm pack` fails on packages with `devEngines`.) +8. Set up the scripts, and build: + - Set the `prepack` script to `tsdown`. + - With pnpm or Yarn 4, point `package.json` at the module's sources, and the same fields in `publishConfig` at `dist`. Set `dev:prepare` to `nuxt-module-build prepare && nuxt prepare playground`. See [Source exports](#source-exports). + - With npm, Yarn 3 or earlier, or bun, set `dev:prepare` to `nuxt-module-build prepare && tsdown && nuxt prepare playground`. See [Developing against dist](#developing-against-dist). + - Run `nuxt-module-build prepare`, then `tsdown`. + - Fix what the build reports. Remove each unsupported build option, and annotate each export in a portability error. Build again until the build passes. +9. Run your module's own type check, such as `nuxt typecheck` or `vue-tsc --noEmit`, and fix what it reports: + - You can ignore a build warning about type errors that the type check doesn't reproduce. + - Annotate exports whose type is inferred through a `#build/*` alias. Otherwise, `dist` declares them as `any`. +10. Check the package: + - Run `pnpm dlx publint`. + - Run `pnpm pack`, then `pnpm dlx @arethetypeswrong/cli -.tgz`. + - Fix any path that they report. `attw --pack .` only works with npm, and `npm pack` fails on packages with `devEngines`. 11. Run your module's tests and the playground.