Skip to content

Nxジェネレータージェネレーター

TypeScriptプロジェクトにNx Generatorを追加し、コンポーネントのスキャフォールディングや特定のプロジェクト構造の強制など、反復的なタスクの自動化を支援します。

使用方法

ジェネレータの生成

ジェネレータは2つの方法で生成できます:

  1. インストール Nx Console VSCode Plugin まだインストールしていない場合
  2. VSCodeでNxコンソールを開く
  3. クリック Generate (UI) "Common Nx Commands"セクションで
  4. 検索 @aws/nx-plugin - ts#nx-generator
  5. 必須パラメータを入力
    • クリック Generate

    オプション

    パラメータ デフォルト 説明
    pluginProject 必須 string - TypeScript project to add the generator to. We recommend creating a ts#project in a top-level 'tools' directory.
    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>)

    ジェネレータの出力

    ジェネレータは指定されたpluginProject内に以下のプロジェクトファイルを作成します:

    • Directorysrc/<name>/
      • schema.json ジェネレータの入力スキーマ
      • schema.d.ts スキーマのTypeScript型定義
      • generator.ts ジェネレータ実装のスタブ
      • generator.spec.ts ジェネレータのテスト
    • generators.json ジェネレータ定義用のNx設定
    • package.json 「generators」エントリが追加または更新
    • tsconfig.json CommonJS使用に更新

    :::警告 このジェネレータは選択したpluginProjectをCommonJS使用に更新します。現時点ではNxジェネレータがCommonJSのみをサポートしているためです(ESMサポートに関するGitHubイシュー)。 :::

    ローカルジェネレータ

    :::ヒント まずts#projectジェネレータを使用して、すべてのジェネレータ用の専用TypeScriptプロジェクトを生成することを推奨します。例:

    1. インストール Nx Console VSCode Plugin まだインストールしていない場合
    2. VSCodeでNxコンソールを開く
    3. クリック Generate (UI) "Common Nx Commands"セクションで
    4. 検索 @aws/nx-plugin - ts#project
    5. 必須パラメータを入力
      • name: nx-plugin
      • directory: tools
    6. クリック Generate

    :::

    ts#nx-generatorジェネレータを実行する際にローカルのnx-pluginプロジェクトを選択し、名前、オプションのディレクトリ、説明を指定します。

    スキーマの定義

    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)

    x-promptプロパティを追加してCLI実行時のプロンプトをカスタマイズ:

    "name": {
    "type": "string",
    "description": "Component name",
    "x-prompt": "コンポーネントの名前を入力してください"
    }

    真偽値オプションにはYes/Noプロンプト:

    "withTests": {
    "type": "boolean",
    "description": "Whether to generate test files",
    "x-prompt": "テストファイルを生成しますか?"
    }

    ドロップダウン選択

    固定選択肢があるオプションにはenumを使用:

    "style": {
    "type": "string",
    "description": "使用するスタイリング手法",
    "enum": ["css", "scss", "styled-components", "none"],
    "default": "css"
    }

    プロジェクト選択ドロップダウン

    ワークスペースの既存プロジェクトから選択させる一般的なパターン:

    "project": {
    "type": "string",
    "description": "コンポーネントを追加するプロジェクト",
    "x-prompt": "コンポーネントを追加するプロジェクトを選択してください",
    "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のように実行可能になります(--name=my-component不要)。

    優先度の設定

    x-priorityプロパティで重要なオプションを指定:

    "name": {
    "type": "string",
    "description": "Component name",
    "x-priority": "important"
    }

    "important"または"internal"を指定可能。Nx VSCode拡張やCLIでのプロパティ表示順序に影響します。

    デフォルト値

    オプションのデフォルト値を設定:

    "directory": {
    "type": "string",
    "description": "コンポーネント生成ディレクトリ",
    "default": "src/components"
    }

    詳細情報

    スキーマの詳細はNx Generator Optionsドキュメントを参照。

    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) {
    // オプションの型がTypeScriptで認識される
    const { name, directory = 'src/components', withTests = true } = options;
    // ...
    }

    ジェネレータの実装

    上記の方法でジェネレータを作成後、generator.tsに実装を記述します。

    ジェネレータは仮想ファイルシステム(Tree)を操作する関数です。変更はジェネレータ終了時(dry-runモードでない場合)に実際のファイルシステムに反映されます。

    一般的な操作例:

    ファイルの読み書き

    // ファイル読み取り
    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')) {
    // 処理
    }

    テンプレートからのファイル生成

    @nx/devkitgenerateFilesユーティリティでEJSテンプレートを使用:

    import { generateFiles, joinPathFragments } from '@nx/devkit';
    // テンプレートからファイル生成
    generateFiles(
    tree,
    joinPathFragments(__dirname, 'files'), // テンプレートディレクトリ
    'path/to/output', // 出力ディレクトリ
    {
    // テンプレート変数
    name: options.name,
    nameCamelCase: camelCase(options.name),
    nameKebabCase: kebabCase(options.name),
    },
    );

    TypeScript AST操作

    AWS向けNxプラグインのtsAstReplaceメソッドでASTを操作:

    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));

    :::ヒント セレクタのテストはTSQuery Playgroundで実施可能です。 :::

    依存関係の追加

    import { addDependenciesToPackageJson } from '@nx/devkit';
    // package.jsonに依存関係追加
    addDependenciesToPackageJson(
    tree,
    {
    'new-dependency': '^1.0.0',
    },
    {
    'new-dev-dependency': '^2.0.0',
    },
    );

    生成ファイルのフォーマット

    import { formatFilesInSubtree } from '@aws/nx-plugin/sdk/utils/format';
    // 変更ファイルのフォーマット
    await formatFilesInSubtree(tree, 'optional/path/to/format');

    JSONファイルの操作

    import { readJson, updateJson } from '@nx/devkit';
    // JSONファイル読み取り
    const packageJson = readJson(tree, 'package.json');
    // JSONファイル更新
    updateJson(tree, 'tsconfig.json', (json) => {
    json.compilerOptions = {
    ...json.compilerOptions,
    strict: true,
    };
    return json;
    });

    AWS向けNxプラグインのジェネレータ拡張

    AWS向けNxプラグインのジェネレータをインポートして拡張可能:

    import { tsProjectGenerator } from '@aws/nx-plugin/sdk/ts';
    export const myGenerator = async (tree: Tree, schema: MyGeneratorSchema) => {
    const callback = await tsProjectGenerator(tree, { ... });
    // TypeScriptプロジェクトジェネレータを拡張
    // 依存関係インストール用コールバックを返す
    return callback;
    };

    OpenAPIジェネレータ

    TypeScriptクライアント生成用ジェネレータを同様に拡張:

    import { openApiTsClientGenerator } from '@aws/nx-plugin/sdk/open-api';
    export const myGenerator = async (tree: Tree, schema: MyGeneratorSchema) => {
    await openApiTsClientGenerator(tree, { ... });
    // 追加ファイル生成
    };

    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,
    joinPathFragments(__dirname, 'files'), // テンプレートディレクトリ
    'path/to/output', // 出力ディレクトリ
    data,
    );
    };

    テンプレート例:

    files/my-operations.ts.template
    export const myOperationNames = [
    <%_ allOperations.forEach((op) => { _%>
    '<%- op.name %>',
    <%_ }); _%>
    ];

    複雑な例はGitHubリポジトリを参照。

    ジェネレータの実行

    2つの方法でジェネレータを実行可能:

    1. インストール Nx Console VSCode Plugin まだインストールしていない場合
    2. VSCodeでNxコンソールを開く
    3. クリック Generate (UI) "Common Nx Commands"セクションで
    4. 検索 @my-project/nx-plugin - my-generator
    5. 必須パラメータを入力
      • クリック Generate

      ジェネレータのテスト

      ジェネレータの単体テスト実装例:

      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',
      sourceRoot: 'src',
      }),
      );
      tree.write('src/existing-file.ts', 'export const existing = true;');
      });
      it('期待するファイルを生成する', async () => {
      // ジェネレータ実行
      await yourGenerator(tree, {
      name: 'test',
      // その他必須オプション
      });
      // ファイル生成確認
      expect(tree.exists('src/test/file.ts')).toBeTruthy();
      // ファイル内容確認
      const content = tree.read('src/test/file.ts', 'utf-8');
      expect(content).toContain('export const test');
      // スナップショットテスト
      expect(tree.read('src/test/file.ts', 'utf-8')).toMatchSnapshot();
      });
      it('既存ファイルを更新する', async () => {
      // ジェネレータ実行
      await yourGenerator(tree, {
      name: 'test',
      // その他必須オプション
      });
      // 既存ファイルの更新確認
      const content = tree.read('src/existing-file.ts', 'utf-8');
      expect(content).toContain('import { test } from');
      });
      it('エラーを適切に処理する', async () => {
      // エラー発生条件のテスト
      await expect(
      yourGenerator(tree, {
      name: 'invalid',
      // エラーを引き起こすオプション
      }),
      ).rejects.toThrow('想定されるエラーメッセージ');
      });
      });

      テストの主要ポイント:

      • createTreeWithEmptyWorkspace()で仮想ファイルシステム作成
      • ジェネレータ実行前の前提条件ファイルをセットアップ
      • 新規ファイル生成と既存ファイル更新の両方をテスト
      • 複雑なファイル内容にはスナップショットテストを使用
      • エラー条件のテストで適切なエラーハンドリングを確認

      @aws/nx-pluginへのジェネレータ提供

      ts#nx-generatorを使用して@aws/nx-plugin内にジェネレータをスキャフォールディング可能です。

      当リポジトリで実行時、以下のファイルが生成されます:

      • Directorypackages/nx-plugin/src/<name>/
        • schema.json ジェネレータ入力スキーマ
        • schema.d.ts TypeScript型定義
        • generator.ts ジェネレータ実装
        • generator.spec.ts テスト
      • Directorydocs/src/content/docs/guides/
        • <name>.mdx ジェネレータドキュメント
      • packages/nx-plugin/generators.json ジェネレータ定義を更新

      実装を開始できます。

      :::ヒント AWS向けNxプラグインへの貢献に関する詳細ガイドはこちらのチュートリアルを参照してください。 :::