diff --git a/docs/module.md b/docs/module.md index e343f1cb4..6b2880133 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, remove, and build Nuxt modules from the command line." links: - label: Source icon: i-simple-icons-github @@ -135,3 +135,77 @@ 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 (default: `dist`) | +| `--sourcemap` | | Emit source maps | + + +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` + + +```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 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`. +:: 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..fbb19e339 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/_builder.ts @@ -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(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 + 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) +} 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..8fe7d3528 --- /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 (default: `dist`)', + }, + sourcemap: { + type: 'boolean', + description: 'Emit source maps', + }, +}) 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..db7509b47 --- /dev/null +++ b/packages/nuxt-cli/src/commands/module/prepare.ts @@ -0,0 +1,3 @@ +import { defineModuleBuilderCommand } from './_builder' + +export default defineModuleBuilderCommand('prepare', 'Prepare a module environment by writing types', {}) 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..3d9204982 --- /dev/null +++ b/packages/nuxt-cli/test/e2e/module-builder.spec.ts @@ -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`.') + }) +}) diff --git a/packages/nuxt-cli/test/unit/help.spec.ts b/packages/nuxt-cli/test/unit/help.spec.ts index c7450e226..b83972d14 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 Prepare a module environment by writing types 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'] },