From 74af69b7f3c4cad9157cf9150ebd4484d42d8294 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 13:17:48 +0000 Subject: [PATCH 1/5] feat(module): add `module build` and `module prepare` commands Run the matching `nuxt-module-build` subcommand of the module's @nuxt/module-builder, offering to install it and its tsdown and typescript peers when they are missing. Amp-Thread-ID: https://ampcode.com/threads/T-01a1e495-67d0-74e5-84ee-4b3630744f61 --- docs/module.md | 70 ++++++- .../nuxt-cli/src/commands/module/_builder.ts | 197 ++++++++++++++++++ .../nuxt-cli/src/commands/module/build.ts | 13 ++ .../nuxt-cli/src/commands/module/index.ts | 2 + .../nuxt-cli/src/commands/module/prepare.ts | 3 + .../nuxt-cli/test/e2e/module-builder.spec.ts | 85 ++++++++ packages/nuxt-cli/test/unit/help.spec.ts | 10 +- scripts/generate-command-docs.ts | 2 + 8 files changed, 377 insertions(+), 5 deletions(-) create mode 100644 packages/nuxt-cli/src/commands/module/_builder.ts create mode 100644 packages/nuxt-cli/src/commands/module/build.ts create mode 100644 packages/nuxt-cli/src/commands/module/prepare.ts create mode 100644 packages/nuxt-cli/test/e2e/module-builder.spec.ts diff --git a/docs/module.md b/docs/module.md index e343f1cb4..dcc3e0e3c 100644 --- a/docs/module.md +++ b/docs/module.md @@ -1,6 +1,6 @@ --- title: "nuxt module" -description: "Search, add and remove modules in your Nuxt application with the command line." +description: "Search, add and remove modules in your Nuxt application, and build your own modules, with the command line." links: - label: Source icon: i-simple-icons-github @@ -135,3 +135,71 @@ npx nuxt module search pinia ``` Use `--json` to get the results as machine-readable JSON. + +## `nuxt module build` + + +```bash [Terminal] +npx nuxt module build [ROOTDIR] [--cwd=] [--outDir=] [--sourcemap] +``` + + +### Arguments + + +| Argument | Description | +|-----------|-----------------------------------------------------| +| `ROOTDIR` | The root directory of your Nuxt module (default: .) | + + +### Options + + +| Option | Default | Description | +|------------------------|---------|----------------------------------------------------------------------------------------------------------| +| `--cwd=` | | Specify the root directory of your Nuxt module | +| `--outDir=` | | Output directory, relative to the module root. Overrides `outDir` in the tsdown config (default: `dist`) | +| `--sourcemap` | | Emit source maps. Overrides `sourcemap` in the tsdown config | + + +The command builds the module in `ROOTDIR` for publishing. It runs the `build` command of [`@nuxt/module-builder`](/docs/guide/modules/module-builder/commands#build) and passes every argument through, so `nuxt module build` is the same as `nuxt-module-build build`. + +If the module does not have `@nuxt/module-builder` installed, the command offers to install it as a development dependency, together with the `tsdown` and `typescript` peer dependencies it builds with, at the versions the module builder requires. Outside an interactive terminal, it prints the install command instead. + +**Example:** + +```bash [Terminal] +npx nuxt module build +``` + +## `nuxt module prepare` + + +```bash [Terminal] +npx nuxt module prepare [ROOTDIR] [--cwd=] +``` + + +### Arguments + + +| Argument | Description | +|-----------|-----------------------------------------------------| +| `ROOTDIR` | The root directory of your Nuxt module (default: .) | + + +### Options + + +| Option | Default | Description | +|---------------------|---------|------------------------------------------------| +| `--cwd=` | | Specify the root directory of your Nuxt module | + + +The command generates the `.nuxt` directory in `ROOTDIR`, which the module's `tsconfig.json` extends. It runs the `prepare` command of [`@nuxt/module-builder`](/docs/guide/modules/module-builder/commands#prepare), and installs it first in the same way as `nuxt module build`. + +**Example:** + +```bash [Terminal] +npx nuxt module prepare +``` diff --git a/packages/nuxt-cli/src/commands/module/_builder.ts b/packages/nuxt-cli/src/commands/module/_builder.ts new file mode 100644 index 000000000..6935c61c7 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/_builder.ts @@ -0,0 +1,197 @@ +import type { ArgsDef } from 'citty' +import type { DetectResult } from 'package-manager-detector' +import type { PackageJson } from 'pkg-types' + +import { readFileSync } from 'node:fs' +import process from 'node:process' +import { styleText } from 'node:util' + +import { cancel, confirm, isCancel } from '@clack/prompts' +import { defineCommand } from 'citty' +import { resolveModulePath } from 'exsolve' +import { resolveCommand } from 'package-manager-detector/commands' +import { dirname, resolve } from 'pathe' +import { x } from 'tinyexec' + +import { ActionableError } from '../../utils/errors' +import { createInstallLog, runInstall } from '../../utils/install' +import { logger } from '../../utils/logger' +import { defaultPackageManager, detectPackageManager } from '../../utils/package-managers' +import { resolveRootDir } from '../../utils/paths' +import { withNodePath } from '../../utils/resolve-nuxt' +import { createSpinner } from '../../utils/spinner' +import { isInteractive } from '../../utils/stdout' +import { globalCwdArgs } from '../_shared' + +const MODULE_BUILDER = '@nuxt/module-builder' +/** Peers of the module builder that `nuxt module` installs alongside it. */ +const PEERS = ['tsdown', 'typescript'] +const WHITESPACE_RE = /\s/ + +const moduleRootArgs = { + rootDir: { + type: 'positional', + description: 'The root directory of your Nuxt module (default: .)', + required: false, + default: undefined, + }, + // Overrides the description of the global `--cwd`, which names a Nuxt project. + cwd: { + ...globalCwdArgs.cwd, + description: 'Specify the root directory of your Nuxt module', + }, +} as const satisfies ArgsDef + +/** + * A `nuxt module` subcommand that runs the same subcommand of the + * `nuxt-module-build` CLI from the module's `@nuxt/module-builder`. + * + * Every argument is forwarded, so flags added to the module builder later work + * without a CLI release; the ones declared here are for `--help` and the docs. + */ +export function defineModuleBuilderCommand(name: 'build' | 'prepare', description: string, args: T) { + return defineCommand({ + meta: { name, description }, + args: { ...moduleRootArgs, ...args }, + async run(ctx) { + const rootDir = resolveRootDir(ctx.args) + const bin = await ensureModuleBuilder(rootDir, name) + + // The arguments are forwarded as given, including a `--cwd` passed before + // `module`, so the module builder reads them exactly as + // `nuxt-module-build` would, even flags this CLI does not declare. + const result = await x(process.execPath, [bin, name, ...ctx.rawArgs], { + nodeOptions: { stdio: 'inherit' }, + throwOnError: false, + }) + if (result.exitCode !== 0) { + process.exit(result.exitCode ?? 1) + } + }, + }) +} + +interface ModuleBuilder { + /** The `nuxt-module-build` script. */ + bin: string + /** The required peers out of {@link PEERS} that this version declares, with their ranges. */ + peers: Record +} + +/** The module's `@nuxt/module-builder`, if it has one with a `nuxt-module-build` command. */ +function resolveModuleBuilder(rootDir: string): ModuleBuilder | undefined { + const manifest = resolveModulePath(`${MODULE_BUILDER}/package.json`, { from: withNodePath(rootDir), try: true, cache: false }) + if (!manifest) { + return + } + const pkg = JSON.parse(readFileSync(manifest, 'utf8')) as Pick + const script = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['nuxt-module-build'] + if (!script) { + return + } + const peers = Object.entries(pkg.peerDependencies ?? {}) + .filter(([name]) => PEERS.includes(name) && !pkg.peerDependenciesMeta?.[name]?.optional) + return { bin: resolve(dirname(manifest), script), peers: Object.fromEntries(peers) } +} + +function isResolvable(rootDir: string, name: string): boolean { + return Boolean(resolveModulePath(name, { from: withNodePath(rootDir), try: true, cache: false })) +} + +/** + * A package spec for `name` at `range`. A range that cannot be part of a spec + * (`*`, `^5.9.3 || ^6.0.0`) falls back to the bare name, as `nuxt module add` + * does for peer dependencies. + */ +function packageSpec(name: string, range: string | undefined): string { + return range && range !== '*' && !WHITESPACE_RE.test(range) ? `${name}@${range}` : name +} + +/** + * The `nuxt-module-build` script of the module's `@nuxt/module-builder`, after + * offering to install the builder and the `tsdown` and `typescript` peers it + * builds with when the module is missing any of them. + */ +async function ensureModuleBuilder(rootDir: string, command: string): Promise { + let builder = resolveModuleBuilder(rootDir) + // Until the builder is installed, the peers it declares are not known, so the + // ones the current release requires are checked. They are only installed + // below if the installed builder declares them. + const missingPeers = (builder ? Object.keys(builder.peers) : PEERS).filter(name => !isResolvable(rootDir, name)) + if (builder && missingPeers.length === 0) { + return builder.bin + } + + const packageManager = await detectPackageManager(rootDir) ?? defaultPackageManager + if (!isInteractive()) { + // Without the builder, the ranges of its peers are not known yet, so only + // the builder is asked for; the next run asks for the peers it declares. + const deps = builder ? missingPeers.map(name => packageSpec(name, builder!.peers[name])) : [MODULE_BUILDER] + throw new ActionableError(`${describeMissing(command, builder ? missingPeers : [MODULE_BUILDER])} Install ${deps.length > 1 ? 'them' : 'it'} with ${styleText('bold', formatInstallCommand(packageManager, deps))}.`) + } + + const missing = [...builder ? [] : [MODULE_BUILDER], ...missingPeers] + const list = formatList(missing) + const message = describeMissing(command, missing) + + logger.warn(message) + const answer = await confirm({ message: `Install ${list} as ${missing.length > 1 ? 'devDependencies' : 'a devDependency'}?`, initialValue: true }) + if (isCancel(answer) || !answer) { + cancel('Skipping installation.') + process.exit(1) + } + + if (!builder) { + await installDevDependencies(rootDir, packageManager, [MODULE_BUILDER]) + builder = resolveModuleBuilder(rootDir) + if (!builder) { + throw new ActionableError(`${MODULE_BUILDER} was installed but its \`nuxt-module-build\` command could not be found.`) + } + } + + // Peers are installed even when the builder's install pulled them into + // `node_modules`, so the module declares the tools its build runs. + const { peers } = builder + const peerSpecs = missingPeers.filter(name => name in peers).map(name => packageSpec(name, peers[name])) + if (peerSpecs.length > 0) { + await installDevDependencies(rootDir, packageManager, peerSpecs) + } + + return builder.bin +} + +async function installDevDependencies(rootDir: string, packageManager: DetectResult, dependencies: string[]): Promise { + const list = formatList(dependencies) + const installLog = createInstallLog() + const spinner = createSpinner({ indicator: 'timer' }) + spinner.start(`Installing ${list} with ${styleText('cyan', packageManager.name)}`) + const result = await runInstall({ + cwd: rootDir, + packageManager, + dependencies, + dev: true, + onOutput: installLog.onOutput, + onStatus: message => spinner.message(message), + }) + if (!result.success) { + spinner.error(result.error ?? 'Install failed') + installLog.finish(result) + throw new ActionableError(`Could not install ${list}. Install ${dependencies.length > 1 ? 'them' : 'it'} with ${styleText('bold', formatInstallCommand(packageManager, dependencies))}.`) + } + spinner.stop(`Installed ${list}`) + installLog.finish(result) +} + +function describeMissing(command: string, missing: string[]): string { + return `${styleText('cyan', `nuxt module ${command}`)} needs ${formatList(missing)}, which ${missing.length > 1 ? 'are' : 'is'} not installed in this module.` +} + +function formatInstallCommand(packageManager: DetectResult, dependencies: string[]): string { + const { command, args } = resolveCommand(packageManager.agent, 'add', ['-D', ...dependencies])! + return [command, ...args].join(' ') +} + +function formatList(names: string[]): string { + const styled = names.map(name => styleText('cyan', name)) + return styled.length > 1 ? `${styled.slice(0, -1).join(', ')} and ${styled.at(-1)}` : styled[0]! +} diff --git a/packages/nuxt-cli/src/commands/module/build.ts b/packages/nuxt-cli/src/commands/module/build.ts new file mode 100644 index 000000000..70cff0c48 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/build.ts @@ -0,0 +1,13 @@ +import { defineModuleBuilderCommand } from './_builder' + +export default defineModuleBuilderCommand('build', 'Build a module for publishing', { + outDir: { + type: 'string', + valueHint: 'directory', + description: 'Output directory, relative to the module root. Overrides `outDir` in the tsdown config (default: `dist`)', + }, + sourcemap: { + type: 'boolean', + description: 'Emit source maps. Overrides `sourcemap` in the tsdown config', + }, +}) diff --git a/packages/nuxt-cli/src/commands/module/index.ts b/packages/nuxt-cli/src/commands/module/index.ts index 01407b028..8432b9872 100644 --- a/packages/nuxt-cli/src/commands/module/index.ts +++ b/packages/nuxt-cli/src/commands/module/index.ts @@ -10,5 +10,7 @@ export default defineCommand({ add: () => import('./add').then(r => r.default || r), remove: () => import('./remove').then(r => r.default || r), search: () => import('./search').then(r => r.default || r), + build: () => import('./build').then(r => r.default || r), + prepare: () => import('./prepare').then(r => r.default || r), }, }) diff --git a/packages/nuxt-cli/src/commands/module/prepare.ts b/packages/nuxt-cli/src/commands/module/prepare.ts new file mode 100644 index 000000000..68ed3b88d --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/prepare.ts @@ -0,0 +1,3 @@ +import { defineModuleBuilderCommand } from './_builder' + +export default defineModuleBuilderCommand('prepare', 'Generate the types of a module', {}) diff --git a/packages/nuxt-cli/test/e2e/module-builder.spec.ts b/packages/nuxt-cli/test/e2e/module-builder.spec.ts new file mode 100644 index 000000000..c0382f3b2 --- /dev/null +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -0,0 +1,85 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import process from 'node:process' +import { fileURLToPath } from 'node:url' + +import { x } from 'tinyexec' +import { afterEach, describe, expect, it } from 'vitest' + +const nuxi = fileURLToPath(new URL('../../bin/nuxi.mjs', import.meta.url)) +const tempDirs: string[] = [] + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) +}) + +async function createModule({ withBuilder, installed = [] }: { withBuilder: boolean, installed?: string[] }) { + const parent = await mkdtemp(join(tmpdir(), 'nuxt-module-builder-')) + tempDirs.push(parent) + const rootDir = join(parent, 'my-module') + await mkdir(rootDir) + await writeFile(join(rootDir, 'package.json'), JSON.stringify({ name: 'my-module' })) + + if (withBuilder) { + // Stands in for `@nuxt/module-builder`: prints what it was run with, and + // exits with a code the CLI has to pass on. + const packageDir = join(rootDir, 'node_modules/@nuxt/module-builder') + await mkdir(packageDir, { recursive: true }) + await writeFile(join(packageDir, 'package.json'), JSON.stringify({ + name: '@nuxt/module-builder', + bin: { 'nuxt-build-module': './cli.mjs', 'nuxt-module-build': './cli.mjs' }, + exports: { './package.json': './package.json' }, + peerDependencies: { tsdown: '^0.23.7', typescript: '^5.9.3 || ^6.0.0' }, + })) + await writeFile(join(packageDir, 'cli.mjs'), 'console.log(JSON.stringify(process.argv.slice(2))); process.exit(3)') + } + + for (const name of installed) { + const packageDir = join(rootDir, 'node_modules', name) + await mkdir(packageDir, { recursive: true }) + await writeFile(join(packageDir, 'package.json'), JSON.stringify({ name, main: './index.js' })) + await writeFile(join(packageDir, 'index.js'), '') + } + + return { parent, rootDir } +} + +function run(args: string[], cwd: string) { + return x('node', [nuxi, ...args], { + // `pnpm` points `NODE_PATH` at this repository's dependencies, which include `tsdown`. + nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', CI: '1', NODE_PATH: '' } }, + }) +} + +describe('nuxt module build', () => { + it('forwards every argument, including a --cwd passed before the command', { timeout: 60_000 }, async () => { + const { parent } = await createModule({ withBuilder: true, installed: ['tsdown', 'typescript'] }) + + // `--unknown` takes a value the CLI cannot know about, so it must not be + // read as ROOTDIR. + const res = await run(['--cwd', 'my-module', 'module', 'build', '--unknown', 'value', '--sourcemap'], parent) + + expect(res.exitCode).toBe(3) + const forwarded = JSON.parse(res.stdout.trim().split('\n').at(-1)!) + expect(forwarded).toEqual(['build', '--cwd', 'my-module', '--unknown', 'value', '--sourcemap']) + }) + + it('prints the install command when the module builder is missing', { timeout: 60_000 }, async () => { + const { rootDir } = await createModule({ withBuilder: false }) + + const res = await run(['module', 'prepare'], rootDir) + + expect(res.exitCode).toBe(1) + expect(res.stdout + res.stderr).toContain('nuxt module prepare needs @nuxt/module-builder, which is not installed in this module. Install it with npm i -D @nuxt/module-builder.') + }) + + it('prints the install command for missing peers at the range the builder declares', { timeout: 60_000 }, async () => { + const { rootDir } = await createModule({ withBuilder: true, installed: ['typescript'] }) + + const res = await run(['module', 'build'], rootDir) + + expect(res.exitCode).toBe(1) + expect(res.stdout + res.stderr).toContain('nuxt module build needs tsdown, which is not installed in this module. Install it with npm i -D tsdown@^0.23.7.') + }) +}) diff --git a/packages/nuxt-cli/test/unit/help.spec.ts b/packages/nuxt-cli/test/unit/help.spec.ts index c7450e226..a4b00d9b7 100644 --- a/packages/nuxt-cli/test/unit/help.spec.ts +++ b/packages/nuxt-cli/test/unit/help.spec.ts @@ -335,13 +335,15 @@ describe('help', () => { expect(await usage(commands.module, main)).toMatchInlineSnapshot(` "Manage Nuxt modules (nuxt module v0.0.0) - USAGE nuxt module add|remove|search + USAGE nuxt module add|remove|search|build|prepare COMMANDS - add Add Nuxt modules - remove Remove Nuxt modules - search Search in Nuxt modules + add Add Nuxt modules + remove Remove Nuxt modules + search Search in Nuxt modules + build Build a module for publishing + prepare Generate the types of a module Use nuxt module --help for more information about a command." `) diff --git a/scripts/generate-command-docs.ts b/scripts/generate-command-docs.ts index 4447a3e72..64c94793a 100644 --- a/scripts/generate-command-docs.ts +++ b/scripts/generate-command-docs.ts @@ -79,6 +79,8 @@ const DOCS: DocEntry[] = [ { id: 'module-add', file: 'module.md', command: ['module', 'add'] }, { id: 'module-remove', file: 'module.md', command: ['module', 'remove'] }, { id: 'module-search', file: 'module.md', command: ['module', 'search'] }, + { id: 'module-build', file: 'module.md', command: ['module', 'build'] }, + { id: 'module-prepare', file: 'module.md', command: ['module', 'prepare'] }, { id: 'prepare', file: 'prepare.md', command: ['prepare'] }, { id: 'preview', file: 'preview.md', command: ['preview'] }, { id: 'task-list', file: 'task.md', command: ['task', 'list'] }, From ce5baf59b3e4f9ae49b00dbbc55463d9da5b788a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 14:21:16 +0000 Subject: [PATCH 2/5] fix(module): install peers within the builder's range and from its import context - Narrow a range of alternatives such as `^5.9.3 || ^6.0.0` to its last one, so TypeScript 7 is not installed for a builder that does not support it. - Resolve peers from the builder's directory without NODE_PATH, which the builder's ES module imports ignore. - Stop the install when the spinner is cancelled. - Name the module directory in install hints when it is not the current one. - Link the module-builder docs where nuxt.com mounts them. Amp-Thread-ID: https://ampcode.com/threads/T-01a1e495-67d0-74e5-84ee-4b3630744f61 --- docs/module.md | 4 +- .../nuxt-cli/src/commands/module/_builder.ts | 41 ++++++++++++------- .../nuxt-cli/test/e2e/module-builder.spec.ts | 11 +++-- 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/docs/module.md b/docs/module.md index dcc3e0e3c..2fa399e03 100644 --- a/docs/module.md +++ b/docs/module.md @@ -162,7 +162,7 @@ npx nuxt module build [ROOTDIR] [--cwd=] [--outDir=] [--so | `--sourcemap` | | Emit source maps. Overrides `sourcemap` in the tsdown config | -The command builds the module in `ROOTDIR` for publishing. It runs the `build` command of [`@nuxt/module-builder`](/docs/guide/modules/module-builder/commands#build) and passes every argument through, so `nuxt module build` is the same as `nuxt-module-build build`. +The command builds the module in `ROOTDIR` for publishing. It runs the `build` command of [`@nuxt/module-builder`](/docs/api/module-builder/commands#build) and passes every argument through, so `nuxt module build` is the same as `nuxt-module-build build`. If the module does not have `@nuxt/module-builder` installed, the command offers to install it as a development dependency, together with the `tsdown` and `typescript` peer dependencies it builds with, at the versions the module builder requires. Outside an interactive terminal, it prints the install command instead. @@ -196,7 +196,7 @@ npx nuxt module prepare [ROOTDIR] [--cwd=] | `--cwd=` | | Specify the root directory of your Nuxt module | -The command generates the `.nuxt` directory in `ROOTDIR`, which the module's `tsconfig.json` extends. It runs the `prepare` command of [`@nuxt/module-builder`](/docs/guide/modules/module-builder/commands#prepare), and installs it first in the same way as `nuxt module build`. +The command generates the `.nuxt` directory in `ROOTDIR`, which the module's `tsconfig.json` extends. It runs the `prepare` command of [`@nuxt/module-builder`](/docs/api/module-builder/commands#prepare), and installs it first in the same way as `nuxt module build`. **Example:** diff --git a/packages/nuxt-cli/src/commands/module/_builder.ts b/packages/nuxt-cli/src/commands/module/_builder.ts index 6935c61c7..323c3503f 100644 --- a/packages/nuxt-cli/src/commands/module/_builder.ts +++ b/packages/nuxt-cli/src/commands/module/_builder.ts @@ -17,7 +17,7 @@ import { ActionableError } from '../../utils/errors' import { createInstallLog, runInstall } from '../../utils/install' import { logger } from '../../utils/logger' import { defaultPackageManager, detectPackageManager } from '../../utils/package-managers' -import { resolveRootDir } from '../../utils/paths' +import { relativeToProcess, resolveRootDir } from '../../utils/paths' import { withNodePath } from '../../utils/resolve-nuxt' import { createSpinner } from '../../utils/spinner' import { isInteractive } from '../../utils/stdout' @@ -74,6 +74,8 @@ export function defineModuleBuilderCommand(name: 'build' | 'p interface ModuleBuilder { /** The `nuxt-module-build` script. */ bin: string + /** The package directory, where its own imports of the peers resolve from. */ + dir: string /** The required peers out of {@link PEERS} that this version declares, with their ranges. */ peers: Record } @@ -91,20 +93,27 @@ function resolveModuleBuilder(rootDir: string): ModuleBuilder | undefined { } const peers = Object.entries(pkg.peerDependencies ?? {}) .filter(([name]) => PEERS.includes(name) && !pkg.peerDependenciesMeta?.[name]?.optional) - return { bin: resolve(dirname(manifest), script), peers: Object.fromEntries(peers) } + return { bin: resolve(dirname(manifest), script), dir: dirname(manifest), peers: Object.fromEntries(peers) } } -function isResolvable(rootDir: string, name: string): boolean { - return Boolean(resolveModulePath(name, { from: withNodePath(rootDir), try: true, cache: false })) +/** + * Whether `name` can be imported from `dir`. `NODE_PATH` is left out because + * the builder imports its peers as ES modules, which ignore it. + */ +function isResolvable(dir: string, name: string): boolean { + return Boolean(resolveModulePath(name, { from: dir, try: true, cache: false })) } /** - * A package spec for `name` at `range`. A range that cannot be part of a spec - * (`*`, `^5.9.3 || ^6.0.0`) falls back to the bare name, as `nuxt module add` - * does for peer dependencies. + * A package spec for `name` within `range`. A range of alternatives + * (`^5.9.3 || ^6.0.0`) is narrowed to its last, conventionally the newest, so + * the spec stays one shell-safe argument without leaving the range. A range + * that still contains whitespace (`>=3 <5`) or is `*` falls back to the bare + * name, as `nuxt module add` does for peer dependencies. */ function packageSpec(name: string, range: string | undefined): string { - return range && range !== '*' && !WHITESPACE_RE.test(range) ? `${name}@${range}` : name + const alternative = range?.split('||').at(-1)?.trim() + return alternative && alternative !== '*' && !WHITESPACE_RE.test(alternative) ? `${name}@${alternative}` : name } /** @@ -117,7 +126,7 @@ async function ensureModuleBuilder(rootDir: string, command: string): Promise !isResolvable(rootDir, name)) + const missingPeers = (builder ? Object.keys(builder.peers) : PEERS).filter(name => !isResolvable(builder?.dir ?? rootDir, name)) if (builder && missingPeers.length === 0) { return builder.bin } @@ -127,7 +136,7 @@ async function ensureModuleBuilder(rootDir: string, command: string): Promise packageSpec(name, builder!.peers[name])) : [MODULE_BUILDER] - throw new ActionableError(`${describeMissing(command, builder ? missingPeers : [MODULE_BUILDER])} Install ${deps.length > 1 ? 'them' : 'it'} with ${styleText('bold', formatInstallCommand(packageManager, deps))}.`) + throw new ActionableError(`${describeMissing(command, builder ? missingPeers : [MODULE_BUILDER])} Install ${deps.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, deps)}.`) } const missing = [...builder ? [] : [MODULE_BUILDER], ...missingPeers] @@ -163,7 +172,8 @@ async function ensureModuleBuilder(rootDir: string, command: string): Promise { const list = formatList(dependencies) const installLog = createInstallLog() - const spinner = createSpinner({ indicator: 'timer' }) + const controller = new AbortController() + const spinner = createSpinner({ indicator: 'timer', onCancel: () => controller.abort() }) spinner.start(`Installing ${list} with ${styleText('cyan', packageManager.name)}`) const result = await runInstall({ cwd: rootDir, @@ -172,11 +182,12 @@ async function installDevDependencies(rootDir: string, packageManager: DetectRes dev: true, onOutput: installLog.onOutput, onStatus: message => spinner.message(message), + signal: controller.signal, }) if (!result.success) { spinner.error(result.error ?? 'Install failed') installLog.finish(result) - throw new ActionableError(`Could not install ${list}. Install ${dependencies.length > 1 ? 'them' : 'it'} with ${styleText('bold', formatInstallCommand(packageManager, dependencies))}.`) + throw new ActionableError(`Could not install ${list}. Install ${dependencies.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, dependencies)}.`) } spinner.stop(`Installed ${list}`) installLog.finish(result) @@ -186,9 +197,11 @@ function describeMissing(command: string, missing: string[]): string { return `${styleText('cyan', `nuxt module ${command}`)} needs ${formatList(missing)}, which ${missing.length > 1 ? 'are' : 'is'} not installed in this module.` } -function formatInstallCommand(packageManager: DetectResult, dependencies: string[]): string { +/** The install command, and the directory to run it in when that is not the current one. */ +function formatInstallCommand(rootDir: string, packageManager: DetectResult, dependencies: string[]): string { const { command, args } = resolveCommand(packageManager.agent, 'add', ['-D', ...dependencies])! - return [command, ...args].join(' ') + const install = styleText('bold', [command, ...args].join(' ')) + return rootDir === resolve('.') ? install : `${install} in ${styleText('cyan', relativeToProcess(rootDir))}` } function formatList(names: string[]): string { diff --git a/packages/nuxt-cli/test/e2e/module-builder.spec.ts b/packages/nuxt-cli/test/e2e/module-builder.spec.ts index c0382f3b2..2e80d1e7d 100644 --- a/packages/nuxt-cli/test/e2e/module-builder.spec.ts +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -47,8 +47,7 @@ async function createModule({ withBuilder, installed = [] }: { withBuilder: bool function run(args: string[], cwd: string) { return x('node', [nuxi, ...args], { - // `pnpm` points `NODE_PATH` at this repository's dependencies, which include `tsdown`. - nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', CI: '1', NODE_PATH: '' } }, + nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', CI: '1' } }, }) } @@ -74,12 +73,12 @@ describe('nuxt module build', () => { expect(res.stdout + res.stderr).toContain('nuxt module prepare needs @nuxt/module-builder, which is not installed in this module. Install it with npm i -D @nuxt/module-builder.') }) - it('prints the install command for missing peers at the range the builder declares', { timeout: 60_000 }, async () => { - const { rootDir } = await createModule({ withBuilder: true, installed: ['typescript'] }) + it('prints the install command for missing peers within the ranges the builder declares', { timeout: 60_000 }, async () => { + const { parent } = await createModule({ withBuilder: true }) - const res = await run(['module', 'build'], rootDir) + const res = await run(['module', 'build', '--cwd', 'my-module'], parent) expect(res.exitCode).toBe(1) - expect(res.stdout + res.stderr).toContain('nuxt module build needs tsdown, which is not installed in this module. Install it with npm i -D tsdown@^0.23.7.') + expect(res.stdout + res.stderr).toContain('nuxt module build needs tsdown and typescript, which are not installed in this module. Install them with npm i -D tsdown@^0.23.7 typescript@^6.0.0 in my-module.') }) }) From 4fbcbaa56eb750333b968c2df8e1d651086b577e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 14:31:32 +0000 Subject: [PATCH 3/5] test(module): disable inherited FORCE_COLOR in the module builder spec Amp-Thread-ID: https://ampcode.com/threads/T-01a1e495-67d0-74e5-84ee-4b3630744f61 --- packages/nuxt-cli/test/e2e/module-builder.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/nuxt-cli/test/e2e/module-builder.spec.ts b/packages/nuxt-cli/test/e2e/module-builder.spec.ts index 2e80d1e7d..ded62aa0e 100644 --- a/packages/nuxt-cli/test/e2e/module-builder.spec.ts +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -47,7 +47,7 @@ async function createModule({ withBuilder, installed = [] }: { withBuilder: bool function run(args: string[], cwd: string) { return x('node', [nuxi, ...args], { - nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', CI: '1' } }, + nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', CI: '1' } }, }) } From 900e14e625e24a105d0c7750e0ba1f050b6d9230 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 16:14:02 +0000 Subject: [PATCH 4/5] chore(module): clean up docs prose and narrated comments Amp-Thread-ID: https://ampcode.com/threads/T-01a1ef23-2a74-7768-a5ea-9bffcb595f6a --- docs/module.md | 8 +-- .../nuxt-cli/src/commands/module/_builder.ts | 72 ++++++------------- .../nuxt-cli/src/commands/module/prepare.ts | 2 +- .../nuxt-cli/test/e2e/module-builder.spec.ts | 4 -- packages/nuxt-cli/test/unit/help.spec.ts | 10 +-- 5 files changed, 30 insertions(+), 66 deletions(-) diff --git a/docs/module.md b/docs/module.md index 2fa399e03..086f822c4 100644 --- a/docs/module.md +++ b/docs/module.md @@ -1,6 +1,6 @@ --- title: "nuxt module" -description: "Search, add and remove modules in your Nuxt application, and build your own modules, with the command line." +description: "Search, add, remove, and build Nuxt modules from the command line." links: - label: Source icon: i-simple-icons-github @@ -162,9 +162,9 @@ npx nuxt module build [ROOTDIR] [--cwd=] [--outDir=] [--so | `--sourcemap` | | Emit source maps. Overrides `sourcemap` in the tsdown config | -The command builds the module in `ROOTDIR` for publishing. It runs the `build` command of [`@nuxt/module-builder`](/docs/api/module-builder/commands#build) and passes every argument through, so `nuxt module build` is the same as `nuxt-module-build build`. +The command builds your module for publishing with [`@nuxt/module-builder`](/docs/api/module-builder/commands#build) and passes all arguments to `nuxt-module-build build`. -If the module does not have `@nuxt/module-builder` installed, the command offers to install it as a development dependency, together with the `tsdown` and `typescript` peer dependencies it builds with, at the versions the module builder requires. Outside an interactive terminal, it prints the install command instead. +If `@nuxt/module-builder`, `tsdown`, or `typescript` aren't installed, it prompts you to install them as dev dependencies. In non-interactive environments, it prints the install command instead. **Example:** @@ -196,7 +196,7 @@ npx nuxt module prepare [ROOTDIR] [--cwd=] | `--cwd=` | | Specify the root directory of your Nuxt module | -The command generates the `.nuxt` directory in `ROOTDIR`, which the module's `tsconfig.json` extends. It runs the `prepare` command of [`@nuxt/module-builder`](/docs/api/module-builder/commands#prepare), and installs it first in the same way as `nuxt module build`. +The command creates the `.nuxt` directory and generates types for your module with [`@nuxt/module-builder`](/docs/api/module-builder/commands#prepare). Like `nuxt module build`, it prompts you to install any missing build dependencies. **Example:** diff --git a/packages/nuxt-cli/src/commands/module/_builder.ts b/packages/nuxt-cli/src/commands/module/_builder.ts index 323c3503f..9dd0632ee 100644 --- a/packages/nuxt-cli/src/commands/module/_builder.ts +++ b/packages/nuxt-cli/src/commands/module/_builder.ts @@ -24,7 +24,6 @@ import { isInteractive } from '../../utils/stdout' import { globalCwdArgs } from '../_shared' const MODULE_BUILDER = '@nuxt/module-builder' -/** Peers of the module builder that `nuxt module` installs alongside it. */ const PEERS = ['tsdown', 'typescript'] const WHITESPACE_RE = /\s/ @@ -35,20 +34,13 @@ const moduleRootArgs = { required: false, default: undefined, }, - // Overrides the description of the global `--cwd`, which names a Nuxt project. cwd: { ...globalCwdArgs.cwd, description: 'Specify the root directory of your Nuxt module', }, } as const satisfies ArgsDef -/** - * A `nuxt module` subcommand that runs the same subcommand of the - * `nuxt-module-build` CLI from the module's `@nuxt/module-builder`. - * - * Every argument is forwarded, so flags added to the module builder later work - * without a CLI release; the ones declared here are for `--help` and the docs. - */ +// `args` populate `--help` and generated docs; `ctx.rawArgs` forwards all flags to `nuxt-module-build`. export function defineModuleBuilderCommand(name: 'build' | 'prepare', description: string, args: T) { return defineCommand({ meta: { name, description }, @@ -57,9 +49,6 @@ export function defineModuleBuilderCommand(name: 'build' | 'p const rootDir = resolveRootDir(ctx.args) const bin = await ensureModuleBuilder(rootDir, name) - // The arguments are forwarded as given, including a `--cwd` passed before - // `module`, so the module builder reads them exactly as - // `nuxt-module-build` would, even flags this CLI does not declare. const result = await x(process.execPath, [bin, name, ...ctx.rawArgs], { nodeOptions: { stdio: 'inherit' }, throwOnError: false, @@ -72,15 +61,11 @@ export function defineModuleBuilderCommand(name: 'build' | 'p } interface ModuleBuilder { - /** The `nuxt-module-build` script. */ bin: string - /** The package directory, where its own imports of the peers resolve from. */ dir: string - /** The required peers out of {@link PEERS} that this version declares, with their ranges. */ peers: Record } -/** The module's `@nuxt/module-builder`, if it has one with a `nuxt-module-build` command. */ function resolveModuleBuilder(rootDir: string): ModuleBuilder | undefined { const manifest = resolveModulePath(`${MODULE_BUILDER}/package.json`, { from: withNodePath(rootDir), try: true, cache: false }) if (!manifest) { @@ -91,59 +76,43 @@ function resolveModuleBuilder(rootDir: string): ModuleBuilder | undefined { if (!script) { return } + const dir = dirname(manifest) const peers = Object.entries(pkg.peerDependencies ?? {}) .filter(([name]) => PEERS.includes(name) && !pkg.peerDependenciesMeta?.[name]?.optional) - return { bin: resolve(dirname(manifest), script), dir: dirname(manifest), peers: Object.fromEntries(peers) } + return { bin: resolve(dir, script), dir, peers: Object.fromEntries(peers) } } -/** - * Whether `name` can be imported from `dir`. `NODE_PATH` is left out because - * the builder imports its peers as ES modules, which ignore it. - */ -function isResolvable(dir: string, name: string): boolean { - return Boolean(resolveModulePath(name, { from: dir, try: true, cache: false })) -} - -/** - * A package spec for `name` within `range`. A range of alternatives - * (`^5.9.3 || ^6.0.0`) is narrowed to its last, conventionally the newest, so - * the spec stays one shell-safe argument without leaving the range. A range - * that still contains whitespace (`>=3 <5`) or is `*` falls back to the bare - * name, as `nuxt module add` does for peer dependencies. - */ +// Pick the last `||` branch (`^5.9.3 || ^6.0.0` -> `^6.0.0`) so union ranges stay a single argument, +// and fall back to the bare name for `*` or ranges with spaces (`>=3 <5`). function packageSpec(name: string, range: string | undefined): string { - const alternative = range?.split('||').at(-1)?.trim() - return alternative && alternative !== '*' && !WHITESPACE_RE.test(alternative) ? `${name}@${alternative}` : name + const target = range?.split('||').at(-1)?.trim() + return target && target !== '*' && !WHITESPACE_RE.test(target) ? `${name}@${target}` : name } -/** - * The `nuxt-module-build` script of the module's `@nuxt/module-builder`, after - * offering to install the builder and the `tsdown` and `typescript` peers it - * builds with when the module is missing any of them. - */ async function ensureModuleBuilder(rootDir: string, command: string): Promise { let builder = resolveModuleBuilder(rootDir) - // Until the builder is installed, the peers it declares are not known, so the - // ones the current release requires are checked. They are only installed - // below if the installed builder declares them. - const missingPeers = (builder ? Object.keys(builder.peers) : PEERS).filter(name => !isResolvable(builder?.dir ?? rootDir, name)) + // Resolve without `NODE_PATH` because ESM imports in `@nuxt/module-builder` ignore it. + const resolveFrom = builder?.dir ?? rootDir + const missingPeers = (builder ? Object.keys(builder.peers) : PEERS) + .filter(name => !resolveModulePath(name, { from: resolveFrom, try: true, cache: false })) if (builder && missingPeers.length === 0) { return builder.bin } const packageManager = await detectPackageManager(rootDir) ?? defaultPackageManager if (!isInteractive()) { - // Without the builder, the ranges of its peers are not known yet, so only - // the builder is asked for; the next run asks for the peers it declares. - const deps = builder ? missingPeers.map(name => packageSpec(name, builder!.peers[name])) : [MODULE_BUILDER] - throw new ActionableError(`${describeMissing(command, builder ? missingPeers : [MODULE_BUILDER])} Install ${deps.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, deps)}.`) + if (builder) { + const { peers } = builder + const deps = missingPeers.map(name => packageSpec(name, peers[name])) + throw new ActionableError(`${describeMissing(command, missingPeers)} Install ${deps.length > 1 ? 'them' : 'it'} with ${formatInstallCommand(rootDir, packageManager, deps)}.`) + } + throw new ActionableError(`${describeMissing(command, [MODULE_BUILDER])} Install it with ${formatInstallCommand(rootDir, packageManager, [MODULE_BUILDER])}.`) } const missing = [...builder ? [] : [MODULE_BUILDER], ...missingPeers] const list = formatList(missing) - const message = describeMissing(command, missing) - logger.warn(message) + logger.warn(describeMissing(command, missing)) const answer = await confirm({ message: `Install ${list} as ${missing.length > 1 ? 'devDependencies' : 'a devDependency'}?`, initialValue: true }) if (isCancel(answer) || !answer) { cancel('Skipping installation.') @@ -158,8 +127,8 @@ async function ensureModuleBuilder(rootDir: string, command: string): Promise name in peers).map(name => packageSpec(name, peers[name])) if (peerSpecs.length > 0) { @@ -197,7 +166,6 @@ function describeMissing(command: string, missing: string[]): string { return `${styleText('cyan', `nuxt module ${command}`)} needs ${formatList(missing)}, which ${missing.length > 1 ? 'are' : 'is'} not installed in this module.` } -/** The install command, and the directory to run it in when that is not the current one. */ function formatInstallCommand(rootDir: string, packageManager: DetectResult, dependencies: string[]): string { const { command, args } = resolveCommand(packageManager.agent, 'add', ['-D', ...dependencies])! const install = styleText('bold', [command, ...args].join(' ')) diff --git a/packages/nuxt-cli/src/commands/module/prepare.ts b/packages/nuxt-cli/src/commands/module/prepare.ts index 68ed3b88d..ed7b78743 100644 --- a/packages/nuxt-cli/src/commands/module/prepare.ts +++ b/packages/nuxt-cli/src/commands/module/prepare.ts @@ -1,3 +1,3 @@ import { defineModuleBuilderCommand } from './_builder' -export default defineModuleBuilderCommand('prepare', 'Generate the types of a module', {}) +export default defineModuleBuilderCommand('prepare', 'Prepare a module for development', {}) diff --git a/packages/nuxt-cli/test/e2e/module-builder.spec.ts b/packages/nuxt-cli/test/e2e/module-builder.spec.ts index ded62aa0e..0dbbadc76 100644 --- a/packages/nuxt-cli/test/e2e/module-builder.spec.ts +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -22,8 +22,6 @@ async function createModule({ withBuilder, installed = [] }: { withBuilder: bool await writeFile(join(rootDir, 'package.json'), JSON.stringify({ name: 'my-module' })) if (withBuilder) { - // Stands in for `@nuxt/module-builder`: prints what it was run with, and - // exits with a code the CLI has to pass on. const packageDir = join(rootDir, 'node_modules/@nuxt/module-builder') await mkdir(packageDir, { recursive: true }) await writeFile(join(packageDir, 'package.json'), JSON.stringify({ @@ -55,8 +53,6 @@ describe('nuxt module build', () => { it('forwards every argument, including a --cwd passed before the command', { timeout: 60_000 }, async () => { const { parent } = await createModule({ withBuilder: true, installed: ['tsdown', 'typescript'] }) - // `--unknown` takes a value the CLI cannot know about, so it must not be - // read as ROOTDIR. const res = await run(['--cwd', 'my-module', 'module', 'build', '--unknown', 'value', '--sourcemap'], parent) expect(res.exitCode).toBe(3) diff --git a/packages/nuxt-cli/test/unit/help.spec.ts b/packages/nuxt-cli/test/unit/help.spec.ts index a4b00d9b7..c9898abea 100644 --- a/packages/nuxt-cli/test/unit/help.spec.ts +++ b/packages/nuxt-cli/test/unit/help.spec.ts @@ -339,11 +339,11 @@ describe('help', () => { COMMANDS - add Add Nuxt modules - remove Remove Nuxt modules - search Search in Nuxt modules - build Build a module for publishing - prepare Generate the types of a module + add Add Nuxt modules + remove Remove Nuxt modules + search Search in Nuxt modules + build Build a module for publishing + prepare Prepare a module for development Use nuxt module --help for more information about a command." `) From 08914545fc2267dba607043f17371165206d01c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Thu, 19 Nov 2026 15:48:02 +0100 Subject: [PATCH 5/5] Apply batched suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sébastien Chopin --- packages/nuxt-cli/src/commands/module/prepare.ts | 2 +- packages/nuxt-cli/test/unit/help.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/nuxt-cli/src/commands/module/prepare.ts b/packages/nuxt-cli/src/commands/module/prepare.ts index ed7b78743..db7509b47 100644 --- a/packages/nuxt-cli/src/commands/module/prepare.ts +++ b/packages/nuxt-cli/src/commands/module/prepare.ts @@ -1,3 +1,3 @@ import { defineModuleBuilderCommand } from './_builder' -export default defineModuleBuilderCommand('prepare', 'Prepare a module for development', {}) +export default defineModuleBuilderCommand('prepare', 'Prepare a module environment by writing types', {}) diff --git a/packages/nuxt-cli/test/unit/help.spec.ts b/packages/nuxt-cli/test/unit/help.spec.ts index c9898abea..b32931873 100644 --- a/packages/nuxt-cli/test/unit/help.spec.ts +++ b/packages/nuxt-cli/test/unit/help.spec.ts @@ -343,7 +343,7 @@ describe('help', () => { remove Remove Nuxt modules search Search in Nuxt modules build Build a module for publishing - prepare Prepare a module for development + prepare Prepare a module environment by writing types Use nuxt module --help for more information about a command." `)