Nxジェネレータージェネレーター
TypeScriptプロジェクトにNx Generatorを追加し、コンポーネントのスキャフォールディングや特定のプロジェクト構造の強制など、反復的なタスクの自動化を支援します。
ジェネレータの生成
Section titled “ジェネレータの生成”ジェネレータは2つの方法で生成できます:
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)
"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - ts#nx-generator
- 必須パラメータを入力
- クリック
Generate
pnpm nx g @aws/nx-plugin:ts#nx-generator
yarn nx g @aws/nx-plugin:ts#nx-generator
npx nx g @aws/nx-plugin:ts#nx-generator
bunx nx g @aws/nx-plugin:ts#nx-generator
変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @aws/nx-plugin:ts#nx-generator --dry-run
yarn nx g @aws/nx-plugin:ts#nx-generator --dry-run
npx nx g @aws/nx-plugin:ts#nx-generator --dry-run
bunx nx g @aws/nx-plugin:ts#nx-generator --dry-run
パラメータ | 型 | デフォルト | 説明 |
---|---|---|---|
project 必須 | string | - | TypeScript project to add the generator to. We recommend using the ts#nx-plugin generator to create this. |
name 必須 | string | - | Generator name |
description | string | - | A description of your generator |
directory | string | - | The directory within the plugin project's source folder to add the generator to (default: <name>) |
ジェネレータの出力
Section titled “ジェネレータの出力”指定したproject
内に以下のプロジェクトファイルが生成されます:
Directorysrc/<name>/
- schema.json ジェネレータの入力スキーマ
- schema.d.ts スキーマのTypeScript型定義
- generator.ts ジェネレータ実装のスタブ
- generator.spec.ts ジェネレータのテスト
- README.md ジェネレータのドキュメント
- generators.json ジェネレータ定義用のNx設定
- package.json “generators”エントリが追加・更新される
- tsconfig.json CommonJS使用に更新される
現在NxジェネレータがCommonJSのみをサポートしているため、このジェネレータは選択したproject
をCommonJS使用に更新します(ESMサポートに関するGitHubイシュー参照)。
ローカルジェネレータ
Section titled “ローカルジェネレータ”ts#nx-generator
ジェネレータを実行する際は、ローカルのnx-plugin
プロジェクトを選択し、名前とオプションのディレクトリ、説明を指定してください。
スキーマの定義
Section titled “スキーマの定義”schema.json
ファイルはジェネレータが受け入れるオプションを定義します。JSON Schema形式とNx拡張仕様に従います。
schema.jsonファイルの基本構造:
{ "$schema": "https://json-schema.org/schema", "$id": "YourGeneratorName", "title": "Your Generator Title", "description": "Description of what your generator does", "type": "object", "properties": { // Your generator options go here }, "required": ["requiredOption1", "requiredOption2"]}
基本的なオプションを含むシンプルな例:
{ "$schema": "https://json-schema.org/schema", "$id": "ComponentGenerator", "title": "Create a Component", "description": "Creates a new React component", "type": "object", "properties": { "name": { "type": "string", "description": "Component name", "x-priority": "important" }, "directory": { "type": "string", "description": "Directory where the component will be created", "default": "src/components" }, "withTests": { "type": "boolean", "description": "Whether to generate test files", "default": true } }, "required": ["name"]}
対話型プロンプト(CLI)
Section titled “対話型プロンプト(CLI)”x-prompt
プロパティを追加してCLI実行時のプロンプトをカスタマイズ:
"name": { "type": "string", "description": "Component name", "x-prompt": "What is the name of your component?"}
真偽値オプションにはyes/noプロンプト:
"withTests": { "type": "boolean", "description": "Whether to generate test files", "x-prompt": "Would you like to generate test files?"}
ドロップダウン選択
Section titled “ドロップダウン選択”固定選択肢にはenum
を使用:
"style": { "type": "string", "description": "The styling approach to use", "enum": ["css", "scss", "styled-components", "none"], "default": "css"}
プロジェクト選択ドロップダウン
Section titled “プロジェクト選択ドロップダウン”ワークスペースの既存プロジェクトから選択:
"project": { "type": "string", "description": "The project to add the component to", "x-prompt": "Which project would you like to add the component to?", "x-dropdown": "projects"}
x-dropdown: "projects"
はNxにワークスペースの全プロジェクトをドロップダウン表示するよう指示します。
コマンドラインの位置引数としてオプションを設定:
"name": { "type": "string", "description": "Component name", "x-priority": "important", "$default": { "$source": "argv", "index": 0 }}
これによりnx g your-generator my-component
のように実行可能になります。
x-priority
プロパティで重要度を表示:
"name": { "type": "string", "description": "Component name", "x-priority": "important"}
"important"
または"internal"
を指定可能。Nx VSCode拡張やCLIでのプロパティ順序付けに役立ちます。
デフォルト値
Section titled “デフォルト値”オプションのデフォルト値を設定:
"directory": { "type": "string", "description": "Directory where the component will be created", "default": "src/components"}
スキーマの詳細はNx Generator Optionsドキュメントを参照。
schema.d.tsによるTypeScript型
Section titled “schema.d.tsによるTypeScript型”schema.json
と共に生成されるschema.d.ts
はジェネレータオプションのTypeScript型を提供:
export interface YourGeneratorSchema { name: string; directory?: string; withTests?: boolean;}
このインターフェースはタイプセーフとコード補完に使用されます:
import { YourGeneratorSchema } from './schema';
export default async function (tree: Tree, options: YourGeneratorSchema) { const { name, directory = 'src/components', withTests = true } = options; // ...}
ジェネレータの実装
Section titled “ジェネレータの実装”上記でジェネレータを生成後、generator.ts
に実装を記述します。
ジェネレータは仮想ファイルシステム(Tree
)を操作する関数です。変更はジェネレータ終了時にディスクに書き込まれます(dry-runモード除く)。空のジェネレータ:
export const myGenerator = async (tree: Tree, options: MyGeneratorSchema) => { // Use the tree to apply changes};
export default myGenerator;
一般的な操作例:
ファイルの読み書き
Section titled “ファイルの読み書き”// ファイル読み込みconst content = tree.read('path/to/file.ts', 'utf-8');
// ファイル書き込みtree.write('path/to/new-file.ts', 'export const hello = "world";');
// ファイル存在確認if (tree.exists('path/to/file.ts')) { // 処理}
テンプレートからのファイル生成
Section titled “テンプレートからのファイル生成”@nx/devkit
のgenerateFiles
でEJSテンプレートを使用:
import { generateFiles, joinPathFragments } from '@nx/devkit';
generateFiles( tree, joinPathFragments(__dirname, 'files'), // テンプレートディレクトリ 'path/to/output', // 出力ディレクトリ { name: options.name, nameCamelCase: camelCase(options.name), // 追加変数 },);
TypeScript AST操作
Section titled “TypeScript AST操作”@aws/nx-plugin/sdk/utils/ast
のtsAstReplace
を使用:
import { tsAstReplace } from '@aws/nx-plugin/sdk/utils/ast';import * as ts from 'typescript';
// バージョン番号更新例tsAstReplace( tree, 'path/to/version.ts', 'VariableDeclaration:has(Identifier[name="VERSION"]) NumericLiteral', (node: ts.NumericLiteral) => ts.factory.createNumericLiteral(Number(node.text) + 1));
依存関係の追加
Section titled “依存関係の追加”import { addDependenciesToPackageJson } from '@nx/devkit';
addDependenciesToPackageJson( tree, { 'new-dependency': '^1.0.0' }, { 'new-dev-dependency': '^2.0.0' },);
生成ファイルのフォーマット
Section titled “生成ファイルのフォーマット”import { formatFilesInSubtree } from '@aws/nx-plugin/sdk/utils/format';
await formatFilesInSubtree(tree, 'optional/path/to/format');
JSONファイルの操作
Section titled “JSONファイルの操作”import { readJson, updateJson } from '@nx/devkit';
// JSON読み込みconst packageJson = readJson(tree, 'package.json');
// JSON更新updateJson(tree, 'tsconfig.json', (json) => { json.compilerOptions.strict = true; return json;});
Nx Plugin for AWSジェネレータの拡張
Section titled “Nx Plugin for AWSジェネレータの拡張”TypeScriptプロジェクトジェネレータを拡張:
import { tsProjectGenerator } from '@aws/nx-plugin/sdk/ts';
export const myGenerator = async (tree: Tree, schema: MyGeneratorSchema) => { const callback = await tsProjectGenerator(tree, { ... }); // 拡張処理 return callback;};
OpenAPIジェネレータ
Section titled “OpenAPIジェネレータ”OpenAPIコード生成データの活用:
import { buildOpenApiCodeGenerationData } from '@aws/nx-plugin/sdk/open-api.js';
export const myGenerator = async (tree: Tree, schema: MyGeneratorSchema) => { const data = await buildOpenApiCodeGenerationData(tree, 'path/to/spec.json'); generateFiles(tree, 'templates', 'output', data);};
テンプレート例:
export const myOperationNames = [<%_ allOperations.forEach((op) => { _%> '<%- op.name %>',<%_ }); _%>];
詳細な例はGitHubリポジトリを参照。
ジェネレータの実行
Section titled “ジェネレータの実行”2つの方法で実行可能:
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)
"Common Nx Commands"セクションで - 検索
@my-project/nx-plugin - my-generator
- 必須パラメータを入力
- クリック
Generate
pnpm nx g @my-project/nx-plugin:my-generator
yarn nx g @my-project/nx-plugin:my-generator
npx nx g @my-project/nx-plugin:my-generator
bunx nx g @my-project/nx-plugin:my-generator
変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @my-project/nx-plugin:my-generator --dry-run
yarn nx g @my-project/nx-plugin:my-generator --dry-run
npx nx g @my-project/nx-plugin:my-generator --dry-run
bunx nx g @my-project/nx-plugin:my-generator --dry-run
ジェネレータのテスト
Section titled “ジェネレータのテスト”単体テストの実装例:
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';import { yourGenerator } from './generator';
describe('your generator', () => { let tree;
beforeEach(() => { tree = createTreeWithEmptyWorkspace(); tree.write('project.json', JSON.stringify({ name: 'test-project' })); });
it('should generate expected files', async () => { await yourGenerator(tree, { name: 'test' }); expect(tree.exists('src/test/file.ts')).toBeTruthy(); expect(tree.read('src/test/file.ts', 'utf-8')).toMatchSnapshot(); });});
テストのポイント:
createTreeWithEmptyWorkspace()
で仮想ファイルシステム作成- 前提ファイルのセットアップ
- 新規ファイル生成と既存ファイル更新のテスト
- スナップショットテストの活用
- エラー条件のテスト
@aws/nx-pluginへのジェネレータ提供
Section titled “@aws/nx-pluginへのジェネレータ提供”ts#nx-generator
を使用して@aws/nx-plugin
内にジェネレータをスキャフォールド可能です。
当リポジトリで実行すると以下のファイルが生成されます:
Directorypackages/nx-plugin/src/<name>/
- schema.json 入力スキーマ
- schema.d.ts 型定義
- generator.ts ジェネレータ実装
- generator.spec.ts テスト
Directorydocs/src/content/docs/guides/
- <name>.mdx ドキュメント
- packages/nx-plugin/generators.json ジェネレータ定義更新