diff --git a/README.md b/README.md index 50182d34..f3ee94d8 100644 --- a/README.md +++ b/README.md @@ -9,204 +9,36 @@ ## 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 +- 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 +- Lets a playground run the module's sources while `package.json` publishes `dist`, and checks the published paths before every build ## 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): `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 +- [Transpiling a directory](./docs/8.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 +47,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..70d7d8e9 --- /dev/null +++ b/docs/1.project-structure.md @@ -0,0 +1,252 @@ +--- +title: Project Structure +description: The files and directories that `@nuxt/module-builder` reads. +--- + +`@nuxt/module-builder` builds a module 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 +โ””โ”€โ”€ tsdown.config.ts # the build configuration +``` + +This page describes what each of these files and directories contains. + +## `src/module.ts` + +`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 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 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. | +| `ModulePublicRuntimeConfig` | `PublicRuntimeConfig` from `@nuxt/schema` | Public runtime config keys the module adds. | + +```ts [src/module.ts] +import { addPlugin, createResolver, defineNuxtModule, updateRuntimeConfig } from '@nuxt/kit' + +export interface ModuleOptions { + greeting: string + apiKey: string +} + +export interface ModuleHooks { + 'my-module:init': (options: ModuleOptions) => void +} + +export interface ModuleRuntimeHooks { + 'my-module:ready': () => void +} + +export interface ModuleRuntimeConfig { + myModule: { apiKey: string } +} + +export interface ModulePublicRuntimeConfig { + myModule: { greeting: string } +} + +export default defineNuxtModule({ + meta: { + name: 'my-module', + configKey: 'myModule', + compatibility: { nuxt: '>=4.0.0' }, + }, + defaults: { + greeting: 'Hello', + apiKey: '', + }, + setup(options) { + const resolver = createResolver(import.meta.url) + + updateRuntimeConfig({ + myModule: { apiKey: options.apiKey }, + public: { myModule: { greeting: options.greeting } }, + }) + addPlugin(resolver.resolve('./runtime/app/plugins/greeting')) + }, +}) +``` + +### 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 + +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/` + +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. 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. + +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. + +### Imports in runtime files + +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: + +```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. + +To transpile another directory in the same way, add it to [`builder({ entries })`](/docs/guide/modules/module-builder/configuration#directory-entries). + +## `playground/` + +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] +{ + "dependencies": { + "my-module": "workspace:*" + } +} +``` + +With npm, list `playground` in the root `workspaces` and use `"my-module": "file:.."`. + +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` + +This is a minimal `package.json` for a module that you publish with pnpm or Yarn 4: + +```json [package.json] +{ + "name": "my-module", + "version": "1.0.0", + "license": "MIT", + "type": "module", + "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": { + "prepack": "tsdown", + "dev": "nuxt dev playground", + "dev:prepare": "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` 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. 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] +{ + "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 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` + +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` + +`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 new file mode 100644 index 00000000..8db0ab03 --- /dev/null +++ b/docs/2.commands.md @@ -0,0 +1,124 @@ +--- +title: Commands +description: Build a module with `tsdown`, and the `nuxt-module-build` commands and their options. +links: + - label: Source + icon: i-simple-icons-github + to: https://github.com/nuxt/module-builder/tree/main/src/commands + size: xs +--- + +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: + +- `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` + +```bash [Terminal] +npx tsdown [--outDir=] [--sourcemap] [--watch] +``` + +`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] +{ + "scripts": { + "prepack": "tsdown" + } +} +``` + +`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. 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` + +```bash [Terminal] +npx nuxt-module-build build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] +``` + +`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. + +### Build steps + +`tsdown` and `build` both run these steps: + +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. + +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 + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| 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`. 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` + +```bash [Terminal] +npx nuxt-module-build prepare [ROOTDIR] [--cwd=] +``` + +`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. + +### How `prepare` loads your module + +`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` fails when the tsdown config sets `cwd` to another directory. tsdown's hooks and plugins don't run for `prepare`. + +Run `prepare` again after you change anything that 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`. | diff --git a/docs/3.develop-and-publish.md b/docs/3.develop-and-publish.md new file mode 100644 index 00000000..8f72c451 --- /dev/null +++ b/docs/3.develop-and-publish.md @@ -0,0 +1,286 @@ +--- +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 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. 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). | + +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. + +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 + +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": "nuxt dev playground", + "dev:prepare": "nuxt-module-build prepare && nuxt prepare playground", + "prepack": "tsdown" + } +} +``` + +`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`. [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, list `playground` in `pnpm-workspace.yaml`, and install the module with `workspace:*` or `link:..`: + +```yaml [pnpm-workspace.yaml] +packages: + - playground +``` + +```json [playground/package.json] +{ + "dependencies": { + "my-module": "workspace:*" + } +} +``` + +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: + +```ts [src/module.ts] +import { addTemplate, defineNuxtModule } from '@nuxt/kit' + +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)}`, + }) + }, +}) +``` + +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 `dist` 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" + } +} +``` + +`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, 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 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: + +```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 the module as you change it: + +- `npm run dev` starts the playground's development server with `nuxt dev 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. 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. 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 [Terminal] +npx tsdown && npx nuxt dev playground +``` + +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 the module yourself first. + +Before your first release, create an account on [npmjs.com](https://www.npmjs.com) and log in with `npm login`. + +### Checking the package + +To check the package before you publish it, follow these steps: + +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" + } +} +``` + +```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: + +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`. 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`: + +```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 + +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: + +- 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 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`. + +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 new file mode 100644 index 00000000..e748c809 --- /dev/null +++ b/docs/4.configuration.md @@ -0,0 +1,248 @@ +--- +title: Configuration +description: Configure the build with `builder()` in `tsdown.config.ts`, build entries other than `src/module.ts`, and keep packages external. +--- + +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' +import { defineConfig } from 'tsdown' + +export default defineConfig({ + plugins: [builder()], +}) +``` + +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' + +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') }, + }), + ], +}) +``` + +## Bundled entries + +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. You can leave out the extension. | +| `name` | The output name. Defaults to `input` without `src/` and without its extension. | + +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. [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: + +```ts [src/utils.ts] +import { normalizeOptions } from './options.ts' + +export function defineMyModuleOptions(options: Record) { + return normalizeOptions(options) +} +``` + +## Directory entries + +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`, 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 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`. + +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`, `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 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 to a function: list the imports instead. + +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 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. 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(), + { + name: 'config-cjs', + generateBundle() { + this.emitFile({ type: 'asset', fileName: 'config.cjs', source: 'module.exports = {}\n' }) + }, + }, + ], +}) +``` + +### Other builds in the same config + +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' +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. It 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. 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`, 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. +- `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. + +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. [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 new file mode 100644 index 00000000..7596e750 --- /dev/null +++ b/docs/5.typescript.md @@ -0,0 +1,218 @@ +--- +title: TypeScript +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. 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. 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 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`. + +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. + +### 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 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] +{ + "extends": "./.nuxt/tsconfig.json" +} +``` + +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" + } +} +``` + +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 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 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.** 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` 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. + +## 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. 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. 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 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 +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 + +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, 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. 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' +import type { NuxtModule } from '@nuxt/schema' + +export interface ModuleOptions { + apiKey: string +} + +const module: NuxtModule = defineNuxtModule({ + meta: { name: 'my-module', configKey: 'myModule' }, + defaults: { apiKey: '' }, + setup() {}, +}) + +export default module +``` + +Without `isolatedDeclarations`, the build prints a reminder once per run outside CI. Both settings work. diff --git a/docs/6.output.md b/docs/6.output.md new file mode 100644 index 00000000..8f6e0d50 --- /dev/null +++ b/docs/6.output.md @@ -0,0 +1,159 @@ +--- +title: Build Output +description: The files that the build writes to `dist`, and the size report it prints. +--- + +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/ +โ”œโ”€โ”€ 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. Set `sourcemap` in `tsdown.config.ts`, or pass `--sourcemap`, to emit a source map next to every script. + +## `module.mjs` + +`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`. The build doesn't bundle them. See [Configuration](/docs/guide/modules/module-builder/configuration#bundled-entries) for the packages that stay external. + +## `module.json` + +`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", + "tsdown": "0.23.7" + } +} +``` + +## `types.d.mts` + +`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' + +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. + +[`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 + +The build emits every file under `src/runtime/` under `dist/runtime/`. It keeps each file's name, 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. 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. 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`. 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: + +```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: + +- 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 + +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`. +- 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, 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] +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/7.exports.md b/docs/7.exports.md new file mode 100644 index 00000000..517a91b7 --- /dev/null +++ b/docs/7.exports.md @@ -0,0 +1,186 @@ +--- +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. 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). + +## Bundled entries + +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] +{ + "exports": { + ".": { + "types": "./dist/types.d.mts", + "import": "./dist/module.mjs" + }, + "./utils": { + "types": "./dist/utils.d.mts", + "import": "./dist/utils.mjs" + } + } +} +``` + +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: + +```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 + +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: + +```ts [src/runtime/app/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/app/components/index.d.ts", + "import": "./dist/runtime/app/components/index.js" + } + } +} +``` + +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/app/components/index'), + prefix: 'My', + }) + }, +}) +``` + +`` 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. +:: + +## 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. 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`. 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 new file mode 100644 index 00000000..63677bc1 --- /dev/null +++ b/docs/8.transpile-dir.md @@ -0,0 +1,120 @@ +--- +title: Transpiling a Directory +description: Use the `transpileDir` rolldown plugin to transpile a directory file by file in any tsdown or rolldown build. +--- + +`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' +import { transpileDir } from '@nuxt/module-builder/rolldown' + +export default defineConfig({ + entry: ['src/index.ts'], + plugins: [ + transpileDir({ srcDir: 'src/runtime', outBase: 'runtime' }), + ], +}) +``` + +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 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. + +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 + +| 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, 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 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] +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 }), + }), + ], +}) +``` + +## 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. 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 new file mode 100644 index 00000000..0b9f320d --- /dev/null +++ b/docs/cli/build-module/index.md @@ -0,0 +1,50 @@ +--- +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] +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. 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 + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| 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. | +| `--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. 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 + +| Argument | Description | +|---|---| +| `ROOTDIR="."` | The module root. | + +### Options + +| Option | Default | Description | +|---|---|---| +| `--cwd=` | | The module root. Takes precedence over `ROOTDIR`. | diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..d5399dba --- /dev/null +++ b/docs/index.md @@ -0,0 +1,108 @@ +--- +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 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. + +`@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 + +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. + +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. 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 + +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` 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 + +To add `@nuxt/module-builder` to an existing module, follow these steps: + +1. Install `@nuxt/module-builder` and its peer dependencies: + + ```bash + pnpm add -D @nuxt/module-builder tsdown@^0.23.7 typescript nuxt + ``` + +2. Create a `tsdown.config.ts` in the module root that uses the `builder()` plugin: + + ```ts [tsdown.config.ts] + import { builder } from '@nuxt/module-builder/tsdown' + import { defineConfig } from 'tsdown' + + export default defineConfig({ + plugins: [builder()], + }) + ``` + +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" + } + } + ``` + +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). + +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 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. +- [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..7e9ed561 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 @@ -373,13 +376,13 @@ 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). ## 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: @@ -456,15 +459,32 @@ 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')) + }, +}) ``` -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. +```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. ## Declaration errors @@ -508,7 +528,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 +541,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,18 +599,18 @@ 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. -- `.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. ## 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 @@ -633,7 +653,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 { @@ -645,7 +665,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" }, @@ -654,8 +673,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", @@ -665,17 +683,28 @@ 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: +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, 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. -- 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. +- **`#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. -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. +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')) +``` + +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. @@ -723,7 +752,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", @@ -732,20 +760,35 @@ 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`. 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 -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. -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`: +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. ```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. @@ -758,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. - -1. Use Node 22.18+, 24.11+, or 26+ 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`). -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. +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. 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. 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..fa17db71 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -24,10 +24,11 @@ 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' +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)) @@ -308,6 +309,33 @@ 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('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')).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)]))) + } + }) +}) + 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')}$`))