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
    パラメータ デフォルト 説明
    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>)

    指定した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イシュー参照)。

    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"]
    }

    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?"
    }

    固定選択肢には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でのプロパティ順序付けに役立ちます。

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

    "directory": {
    "type": "string",
    "description": "Directory where the component will be created",
    "default": "src/components"
    }

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

    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;
    // ...
    }

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

    ジェネレータは仮想ファイルシステム(Tree)を操作する関数です。変更はジェネレータ終了時にディスクに書き込まれます(dry-runモード除く)。空のジェネレータ:

    export const myGenerator = async (tree: Tree, options: MyGeneratorSchema) => {
    // Use the tree to apply changes
    };
    export default myGenerator;

    一般的な操作例:

    // ファイル読み込み
    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/devkitgenerateFilesでEJSテンプレートを使用:

    import { generateFiles, joinPathFragments } from '@nx/devkit';
    generateFiles(
    tree,
    joinPathFragments(__dirname, 'files'), // テンプレートディレクトリ
    'path/to/output', // 出力ディレクトリ
    {
    name: options.name,
    nameCamelCase: camelCase(options.name),
    // 追加変数
    },
    );

    @aws/nx-plugin/sdk/utils/asttsAstReplaceを使用:

    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));
    import { addDependenciesToPackageJson } from '@nx/devkit';
    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');
    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コード生成データの活用:

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

    テンプレート例:

    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' }));
      });
      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 ジェネレータ定義更新