Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion docs/module.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: "nuxt module"
description: "Search, add and remove modules in your Nuxt application with the command line."
description: "Search, add, remove, and build Nuxt modules from the command line."
links:
- label: Source
icon: i-simple-icons-github
Expand Down Expand Up @@ -135,3 +135,71 @@ npx nuxt module search pinia
```

Use `--json` to get the results as machine-readable JSON.

## `nuxt module build`

<!--module-build-cmd-->
```bash [Terminal]
npx nuxt module build [ROOTDIR] [--cwd=<directory>] [--outDir=<directory>] [--sourcemap]
```
<!--/module-build-cmd-->

### Arguments

<!--module-build-args-->
| Argument | Description |
|-----------|-----------------------------------------------------|
| `ROOTDIR` | The root directory of your Nuxt module (default: .) |
<!--/module-build-args-->

### Options

<!--module-build-opts-->
| Option | Default | Description |
|------------------------|---------|----------------------------------------------------------------------------------------------------------|
| `--cwd=<directory>` | | Specify the root directory of your Nuxt module |
| `--outDir=<directory>` | | 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 |
<!--/module-build-opts-->

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 `@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:**

```bash [Terminal]
npx nuxt module build
```

## `nuxt module prepare`

<!--module-prepare-cmd-->
```bash [Terminal]
npx nuxt module prepare [ROOTDIR] [--cwd=<directory>]
```
<!--/module-prepare-cmd-->

### Arguments

<!--module-prepare-args-->
| Argument | Description |
|-----------|-----------------------------------------------------|
| `ROOTDIR` | The root directory of your Nuxt module (default: .) |
<!--/module-prepare-args-->

### Options

<!--module-prepare-opts-->
| Option | Default | Description |
|---------------------|---------|------------------------------------------------|
| `--cwd=<directory>` | | Specify the root directory of your Nuxt module |
<!--/module-prepare-opts-->

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:**

```bash [Terminal]
npx nuxt module prepare
```
178 changes: 178 additions & 0 deletions packages/nuxt-cli/src/commands/module/_builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
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 { relativeToProcess, 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'
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,
},
cwd: {
...globalCwdArgs.cwd,
description: 'Specify the root directory of your Nuxt module',
},
} as const satisfies ArgsDef

// `args` populate `--help` and generated docs; `ctx.rawArgs` forwards all flags to `nuxt-module-build`.
export function defineModuleBuilderCommand<T extends ArgsDef>(name: 'build' | 'prepare', description: string, args: T) {
return defineCommand({
meta: { name, description },
args: { ...moduleRootArgs, ...args },
async run(ctx) {
const rootDir = resolveRootDir(ctx.args)
Comment thread
atinux marked this conversation as resolved.
Resolved
const bin = await ensureModuleBuilder(rootDir, name)

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 {
bin: string
dir: string
peers: Record<string, string>
}

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<PackageJson, 'bin' | 'peerDependencies' | 'peerDependenciesMeta'>
const script = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['nuxt-module-build']
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(dir, script), dir, peers: Object.fromEntries(peers) }
}

// 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 target = range?.split('||').at(-1)?.trim()
return target && target !== '*' && !WHITESPACE_RE.test(target) ? `${name}@${target}` : name
}

async function ensureModuleBuilder(rootDir: string, command: string): Promise<string> {
let builder = resolveModuleBuilder(rootDir)
// 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()) {
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)

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.')
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.`)
}
}

// Reuse `missingPeers` from before installing the builder so auto-installed peers
// are still added to the module's own `devDependencies`.
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<void> {
const list = formatList(dependencies)
const installLog = createInstallLog()
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,
packageManager,
dependencies,
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 ${formatInstallCommand(rootDir, 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(rootDir: string, packageManager: DetectResult, dependencies: string[]): string {
const { command, args } = resolveCommand(packageManager.agent, 'add', ['-D', ...dependencies])!
const install = styleText('bold', [command, ...args].join(' '))
return rootDir === resolve('.') ? install : `${install} in ${styleText('cyan', relativeToProcess(rootDir))}`
}

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]!
}
13 changes: 13 additions & 0 deletions packages/nuxt-cli/src/commands/module/build.ts
Original file line number Diff line number Diff line change
@@ -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',
},
})
2 changes: 2 additions & 0 deletions packages/nuxt-cli/src/commands/module/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
})
3 changes: 3 additions & 0 deletions packages/nuxt-cli/src/commands/module/prepare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineModuleBuilderCommand } from './_builder'

export default defineModuleBuilderCommand('prepare', 'Prepare a module environment by writing types', {})
80 changes: 80 additions & 0 deletions packages/nuxt-cli/test/e2e/module-builder.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
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) {
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], {
nodeOptions: { cwd, env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', CI: '1' } },
})
}

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'] })

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 within the ranges the builder declares', { timeout: 60_000 }, async () => {
const { parent } = await createModule({ withBuilder: true })

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 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.')
})
})
10 changes: 6 additions & 4 deletions packages/nuxt-cli/test/unit/help.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,16 +332,18 @@
})

it('nuxt module', async () => {
expect(await usage(commands.module, main)).toMatchInlineSnapshot(`

Check failure on line 335 in packages/nuxt-cli/test/unit/help.spec.ts

View workflow job for this annotation

GitHub Actions / ci (windows-latest)

packages/nuxt-cli/test/unit/help.spec.ts > help > nuxt module

Error: Snapshot `help > nuxt module 1` mismatched - Expected + Received @@ -2,12 +2,12 @@ USAGE nuxt module add|remove|search|build|prepare COMMANDS - add Add Nuxt modules + add Add Nuxt modules - remove Remove Nuxt modules + remove Remove Nuxt modules - search Search in Nuxt modules + search Search in Nuxt modules - build Build a module for publishing + build Build a module for publishing prepare Prepare a module environment by writing types Use nuxt module <command> --help for more information about a command." ❯ packages/nuxt-cli/test/unit/help.spec.ts:335:48

Check failure on line 335 in packages/nuxt-cli/test/unit/help.spec.ts

View workflow job for this annotation

GitHub Actions / ci (ubuntu-latest)

packages/nuxt-cli/test/unit/help.spec.ts > help > nuxt module

Error: Snapshot `help > nuxt module 1` mismatched - Expected + Received @@ -2,12 +2,12 @@ USAGE nuxt module add|remove|search|build|prepare COMMANDS - add Add Nuxt modules + add Add Nuxt modules - remove Remove Nuxt modules + remove Remove Nuxt modules - search Search in Nuxt modules + search Search in Nuxt modules - build Build a module for publishing + build Build a module for publishing prepare Prepare a module environment by writing types Use nuxt module <command> --help for more information about a command." ❯ packages/nuxt-cli/test/unit/help.spec.ts:335:48

Check failure on line 335 in packages/nuxt-cli/test/unit/help.spec.ts

View workflow job for this annotation

GitHub Actions / ci (macos-latest)

packages/nuxt-cli/test/unit/help.spec.ts > help > nuxt module

Error: Snapshot `help > nuxt module 1` mismatched - Expected + Received @@ -2,12 +2,12 @@ USAGE nuxt module add|remove|search|build|prepare COMMANDS - add Add Nuxt modules + add Add Nuxt modules - remove Remove Nuxt modules + remove Remove Nuxt modules - search Search in Nuxt modules + search Search in Nuxt modules - build Build a module for publishing + build Build a module for publishing prepare Prepare a module environment by writing types Use nuxt module <command> --help for more information about a command." ❯ packages/nuxt-cli/test/unit/help.spec.ts:335:48
"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 Prepare a module environment by writing types

Use nuxt module <command> --help for more information about a command."
`)
Expand Down
2 changes: 2 additions & 0 deletions scripts/generate-command-docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'] },
Expand Down
Loading