Skip to content
Merged
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
76 changes: 75 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,77 @@ 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 (default: `dist`) |
| `--sourcemap` | | Emit source maps |
<!--/module-build-opts-->

The command builds your module for publishing by running `nuxt-module-build build` from `@nuxt/module-builder` with all arguments passed through. `@nuxt/module-builder` must be installed in your module.

**Example:**

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

::read-more{to="https://github.com/nuxt/module-builder/blob/main/docs/2.commands.md#build" icon="i-simple-icons-github" target="\_blank"}
Read more about `nuxt-module-build 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 by running `nuxt-module-build prepare` from `@nuxt/module-builder` with all arguments passed through.

**Example:**

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

::read-more{to="https://github.com/nuxt/module-builder/blob/main/docs/2.commands.md#prepare" icon="i-simple-icons-github" target="\_blank"}
Read more about `nuxt-module-build prepare`.
::
59 changes: 59 additions & 0 deletions packages/nuxt-cli/src/commands/module/_builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { ArgsDef } from 'citty'
import type { PackageJson } from 'pkg-types'

import { readFileSync } from 'node:fs'
import process from 'node:process'

import { defineCommand } from 'citty'
import { resolveModulePath } from 'exsolve'
import { dirname, resolve } from 'pathe'
import { x } from 'tinyexec'

import { ActionableError } from '../../utils/errors'
import { resolveRootDir } from '../../utils/paths'
import { withNodePath } from '../../utils/resolve-nuxt'
import { globalCwdArgs } from '../_shared'

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` only populate `--help` and the generated docs; `ctx.rawArgs` is forwarded as-is.
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 bin = resolveModuleBuilderBin(resolveRootDir(ctx.args), 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)
}
},
})
}

function resolveModuleBuilderBin(rootDir: string, command: string): string {
const manifest = resolveModulePath('@nuxt/module-builder/package.json', { from: withNodePath(rootDir), try: true })
if (!manifest) {
throw new ActionableError(`\`@nuxt/module-builder\` is not installed in this module. Install it as a development dependency to use \`nuxt module ${command}\`.`)
}
const { bin } = JSON.parse(readFileSync(manifest, 'utf8')) as Pick<PackageJson, 'bin'>
const script = typeof bin === 'object' ? bin['nuxt-module-build'] : undefined
if (!script) {
throw new ActionableError(`The installed version of \`@nuxt/module-builder\` does not support \`nuxt module ${command}\`.`)
}
return resolve(dirname(manifest), script)
}
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 (default: `dist`)',
},
sourcemap: {
type: 'boolean',
description: 'Emit source maps',
},
})
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', {})
82 changes: 82 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,82 @@
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, bin = 'nuxt-module-build' }: { withBuilder: boolean, bin?: 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: { [bin]: './cli.mjs' },
exports: { './package.json': './package.json' },
}))
await writeFile(join(packageDir, 'cli.mjs'), 'console.log(JSON.stringify(process.argv.slice(2))); process.exit(3)')
}

return { parent, rootDir }
}

function run(args: string[], cwd: string) {
return x('node', [nuxi, ...args], {
nodeOptions: { cwd, env: { ...process.env, NODE_PATH: undefined, 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 })

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

const res = await run(['module', 'prepare', 'my-module'], parent)

expect(res.exitCode).toBe(3)
const forwarded = JSON.parse(res.stdout.trim().split('\n').at(-1)!)
expect(forwarded).toEqual(['prepare', 'my-module'])
})

it('reports a missing module builder', { 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-builder` is not installed in this module. Install it as a development dependency to use `nuxt module prepare`.')
})

it('reports a module builder without the nuxt-module-build binary', { timeout: 60_000 }, async () => {
const { rootDir } = await createModule({ withBuilder: true, bin: 'nuxt-build-module' })

const res = await run(['module', 'build'], rootDir)

expect(res.exitCode).toBe(1)
expect(res.stdout + res.stderr).toContain('The installed version of `@nuxt/module-builder` does not support `nuxt module build`.')
})
})
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 @@ -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 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