Nx 생성기 생성기
TypeScript 프로젝트에 Nx Generator를 추가하여 컴포넌트 스캐폴딩이나 특정 프로젝트 구조 강제화와 같은 반복 작업을 자동화할 수 있습니다.
사용 방법
생성기 생성
생성기는 두 가지 방법으로 생성할 수 있습니다:
- 설치 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
옵션
매개변수 | 타입 | 기본값 | 설명 |
---|---|---|---|
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
내에 다음 프로젝트 파일들을 생성합니다:
디렉터리src/<name>/
- schema.json 생성자 입력을 위한 스키마
- schema.d.ts 스키마의 TypeScript 타입
- generator.ts 생성자 구현 스텁
- generator.spec.ts 생성자 테스트
- generators.json 생성자 정의를 위한 Nx 설정
- package.json 생성되거나 “generators” 항목이 추가됨
- tsconfig.json CommonJS 사용으로 업데이트됨
이 생성기는 현재 Nx Generator가 CommonJS만 지원하기 때문에 선택한 pluginProject
를 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"]}
대화형 프롬프트 (CLI)
CLI에서 생성기를 실행할 때 표시되는 프롬프트를 사용자 정의하려면 x-prompt
속성을 추가하세요:
"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"}
프로젝트 선택 드롭다운
작업 공간의 기존 프로젝트 중에서 선택하도록 하는 일반적인 패턴:
"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 --name=my-component
대신 nx g your-generator my-component
처럼 실행할 수 있습니다.
우선순위 설정
x-priority
속성을 사용하여 가장 중요한 옵션을 표시합니다:
"name": { "type": "string", "description": "Component name", "x-priority": "important"}
옵션은 "important"
또는 "internal"
우선순위를 가질 수 있습니다. 이는 Nx VSCode 확장과 Nx CLI에서 속성 순서를 지정하는 데 도움이 됩니다.
기본값
옵션에 기본값을 제공할 수 있습니다:
"directory": { "type": "string", "description": "Directory where the component will be created", "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
)을 변형하는 함수로, 원하는 변경 사항을 만들기 위해 파일을 읽고 씁니다. 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/devkit
의 generateFiles
유틸리티를 사용하여 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
메서드를 사용하여 TypeScript 추상 구문 트리의 일부를 교체할 수 있습니다.
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';
// 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 플러그인에서 생성자를 가져와 확장하거나 조합할 수 있습니다. 예를 들어 TypeScript 프로젝트를 기반으로 생성자를 만들 수 있습니다:
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, );};
이를 통해 다음과 같은 템플릿을 작성할 수 있습니다:
export const myOperationNames = [<%_ allOperations.forEach((op) => { _%> '<%- op.name %>',<%_ }); _%>];
더 복잡한 예제 템플릿은 GitHub의 코드베이스를 참조하세요.
생성자 실행
생성자는 두 가지 방법으로 실행할 수 있습니다:
- 설치 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
생성자 테스트
생성자의 단위 테스트는 간단하게 구현할 수 있습니다. 일반적인 패턴 예시:
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('should generate expected files', 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('should update existing files', async () => { // 생성자 실행 await yourGenerator(tree, { name: 'test', // 다른 필수 옵션 추가 });
// 기존 파일 업데이트 확인 const content = tree.read('src/existing-file.ts', 'utf-8'); expect(content).toContain('import { test } from'); });
it('should handle errors', async () => { // 특정 조건에서 생성자가 오류를 발생시키는지 확인 await expect( yourGenerator(tree, { name: 'invalid', // 오류를 유발하는 옵션 추가 }), ).rejects.toThrow('Expected error message'); });});
생성자 테스트의 주요 포인트:
- 가상 파일 시스템 생성에
createTreeWithEmptyWorkspace()
사용 - 생성자 실행 전 필수 파일 설정
- 새 파일 생성과 기존 파일 업데이트 모두 테스트
- 복잡한 파일 내용에 스냅샷 사용
- 생성자가 우아하게 실패하는지 확인하기 위해 오류 조건 테스트
@aws/nx-plugin에 생성자 기여
ts#nx-generator
를 사용하여 @aws/nx-plugin
내부에 생성자 스캐폴딩을 할 수도 있습니다.
이 생성자를 우리 저장소에서 실행하면 다음 파일들이 생성됩니다:
디렉터리packages/nx-plugin/src/<name>/
- schema.json 생성자 입력을 위한 스키마
- schema.d.ts 스키마의 TypeScript 타입
- generator.ts 생성자 구현
- generator.spec.ts 생성자 테스트
디렉터리docs/src/content/docs/guides/
- <name>.mdx 생성자 문서 페이지
- packages/nx-plugin/generators.json 생성자 포함하도록 업데이트됨
이제 생성자 구현을 시작할 수 있습니다.