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": { // 생성기 옵션 작성 위치 }, "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": "What is the name of your component?"}
불리언 옵션의 경우 예/아니오 프롬프트 사용:
"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
과 함께 생성기는 생성기 옵션에 대한 TypeScript 타입을 제공하는 schema.d.ts
파일을 생성합니다:
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')) { // 작업 수행}
템플릿에서 파일 생성
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 (추상 구문 트리) 조작
AST 조작을 위해 TSQuery 설치를 권장합니다.
import { tsquery } from '@phenomnomnominal/tsquery';import * as ts from 'typescript';
// 예시: 파일 내 버전 번호 증가
// 파일 내용을 TypeScript AST로 파싱const sourceFile = tsquery.ast(tree.read('path/to/version.ts', 'utf-8'));
// 셀렉터에 매칭되는 노드 찾기const nodes = tsquery.query( sourceFile, 'VariableDeclaration:has(Identifier[name="VERSION"]) NumericLiteral',);
if (nodes.length > 0) { // 숫자 리터럴 노드 가져오기 const numericNode = nodes[0] as ts.NumericLiteral;
// 현재 버전 번호 가져와 증가 const currentVersion = Number(numericNode.text); const newVersion = currentVersion + 1;
// AST에서 노드 교체 const result = tsquery.replace( sourceFile, 'VariableDeclaration:has(Identifier[name="VERSION"]) NumericLiteral', () => ts.factory.createNumericLiteral(newVersion), );
// 업데이트된 내용을 트리에 다시 쓰기 tree.write( 'path/to/version.ts', ts .createPrinter({ newLine: ts.NewLineKind.LineFeed, }) .printNode(ts.EmitHint.Unspecified, result, sourceFile), );}
의존성 추가
import { addDependenciesToPackageJson } from '@nx/devkit';
// package.json에 의존성 추가addDependenciesToPackageJson( tree, { 'new-dependency': '^1.0.0', }, { 'new-dev-dependency': '^2.0.0', },);
생성된 파일 포맷팅
import { formatFiles } from '@nx/devkit';
// 수정된 모든 파일 포맷팅await formatFiles(tree);
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;});
생성기 실행
두 가지 방법으로 생성기를 실행할 수 있습니다:
- 설치 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 생성기가 포함되도록 업데이트됨
이제 생성기 구현을 시작할 수 있습니다.