hygen을 통해 생성 - 대화 형식의 Component 초기 -

Component를 만들 때 storybook과test도 한 번에 제출하는 장면이 늘었다.또한 CSS Modules, 특정 Component 전용의custom hooks 등 하나의 Component 파일 그룹을 구성하여 해당하는 양이 된다.예를 들어, 다음 module로 구성된 Component입니다.이걸 수공으로 만들면 좀 귀찮겠지.
└── atoms
    └── Button
        ├── Button.stories.tsx
        ├── Button.test.tsx
        ├── Button.tsx
        ├── dependencies.ts
        ├── index.tsx
        └── style.module.css
제작 시 Button의 이름만 결정되어 CLI에서 초기 형태를 출력할 수 있다면 생산성이 향상될 것으로 예상된다.(storybook/test도 쓰세요...! 이런 습관이 생긴 것 같아요) 요즘 제가 불평을 늘어놓을 때 팬들에게서 노드를 얻었어요.js제template gener 도구hygen을 가르쳐 주십시오.(공식: https://www.hygen.io

hygen과의 대화 예시


자신이 한 대화의 예를 소개하다.
https://github.com/takefumi-yoshii/hygen-sanbox
npm scripts에 new:fc 이 script를 등록했습니다.실행하면...
$ npm run new:fc
1."Atomic Design의 카테고리는 무엇입니까?"
? Which Atomic Design category? … 
❯ atoms
  molecules
  organisms
  templates
2."Component 이름이 뭐예요?"
? What is the name of component? · Button
3."어떤 디렉터리예요?"
? Where is the directory? (No problem in blank) ›  buttons
4.'스타일 있어요?'
? Is it have style? (y/N) · true
5.'프롭스 있어요?'
? Is it have props? (y/N) · true
6.'훅스 있어요?'
? Is it have hooks? (y/N) › true
이 대화를 통해 파일은 대화 내용에 따라 자동으로 생성됩니다.
✔ Which Atomic Design category? · atoms
✔ What is the name of component? · Button
✔ Where is the directory? (No problem in blank) · buttons
✔ Is it have style? (y/N) · true
✔ Is it have props? (y/N) · true
✔ Is it have hooks? (y/N) · true

Loaded templates: .hygen
       added: src/components/atoms/buttons/Button/Button.stories.tsx
       added: src/components/atoms/buttons/Button/Button.test.tsx
       added: src/components/atoms/buttons/Button/Button.tsx
       added: src/components/atoms/buttons/Button/dependencies.ts
       added: src/components/atoms/buttons/Button/index.tsx
       added: src/components/atoms/buttons/Button/style.module.css
✨  Done in 7.58s.
파일 이름뿐만 아니라 출력 내용도 대화에서 얻은 변수의 적용 여부를 확인할 수 있다.수작업이 번거로운 부분은 자동화되기 때문에 즐겁다.
【src/components/atoms/buttons/Button/Button.stories.tsx】
import React from "react";
import { storiesOf } from "@storybook/react";
import { Button } from "./";
// ______________________________________________________
//
storiesOf("atoms/buttons/Button", module)
  .add("default", () => <Button />);

자제하는 곳


hygen은 FW를 통째로 접은'그 부분만'의 느낌을 잘 잘랐다.준비된ejs의template는 완전히 자제할 수 있습니다.상술한 Button.stories.tsx는 아래의template에서 생성된 것이다.
---
to: ___EJS0___/___EJS1___.stories.tsx
---
import React from "react";
import { storiesOf } from "@storybook/react";
import { ___EJS2___ } from "./";
// ______________________________________________________
//
storiesOf("___EJS3___", module)
  .add("default", () => <___EJS4___ />);

대화를 설정하는 예는 비교적 선진적인 이용 방법이지만 질문 내용을 설정하는 경우 이런 question object를 자유롭게 재구성하고 prompt.js부터 배열에 따라 export를 진행한다.
{
  type: 'select',   // 入力の種類 [input/confirm/select]
  name: 'category', // process 上で扱われる変数名
  message: 'Which Atomic Design category?', // 対話メッセージ
  choices: ['atoms', 'molecules', 'organisms', 'templates'] // 値
}
출력 지점도template 단위에 따라 분배할 수 있기 때문에 현재의 작업 절차와 결합하여 작업 자동화를 가져올 수 있다.이 경우 동일한 내용을 __stories____tests__로 나눌 수 있습니다.
 added: __stories__/components/atoms/buttons/Button/Button.stories.tsx
 added: __tests__/components/atoms/buttons/Button/Button.test.tsx
 added: src/components/atoms/buttons/Button/Button.tsx
 added: src/components/atoms/buttons/Button/index.tsx
 added: src/components/atoms/buttons/Button/style.module.css
대화에서 얻은 변수를 바탕으로 출력 판단Conditional Rendering을 하고,'스타일 시트가 필요 없다'고 답하면 파일 출력과 import 문장을 삭제한다.
 added: __tests__/components/atoms/buttons/Button/Button.test.tsx
 added: src/components/atoms/buttons/Button/Button.tsx
 added: src/components/atoms/buttons/Button/index.tsx
이번에 Component 모형을 생성하였는데, 공식적으로 소개한 Redux/Express/RN의 예와 같이 정형 작업이라면 대상은 모두 가능하다.기존 파일의 일부에 템플릿을 추가하는 활용 방법이 있기 때문에 정형 작업에 적합한 도구라고 할 수 있다.

견본에 공을 들인 곳


hygen이 할 수 있는 일은 많지만 공식 문서는 그다지 충실하지 않다.찾은 issue에 따라 프로모션 설정을 진행했습니다.
참조: https://github.com/jondot/hygen/issues/35
제작에 들어가면 입력한 내용과 CLI 매개 변수에 따라 고도의 변수가 계산된다.그러나generator 디렉터리에 설정된 prompt.js 파일에서는 할 수 있는 일이 제한되어 있습니다.이 디렉터리index.js에 정의를 쓰면 이번에 소개한 대화 내용에 따라 변수를 계산할 수 있다.prompt 함수 매개 변수inquirer.prompt에 문제가 있는 그룹이 있으면 answers 매개 변수를 얻을 수 있고 반환값은 변수로 ejs templates에 제공됩니다.
【.hygen/new/fc/index.js】
module.exports = {
  prompt: ({ inquirer, args }) => {
    const questions = [
      {
        type: 'select',
        name: 'category',
        message: 'Which Atomic Design category?',
        choices: ['atoms', 'molecules', 'organisms', 'templates']
      },
      {
        type: 'input',
        name: 'component_name',
        message: 'What is the name of component?'
      },
      {
        type: 'input',
        name: 'dir',
        message: 'Where is the directory? (No problem in blank)',
      },
      {
        type: 'confirm',
        name: 'have_style',
        message: 'Is it have style?',
      },
      {
        type: 'confirm',
        name: 'have_props',
        message: 'Is it have props?',
      },
      {
        type: 'confirm',
        name: 'have_hooks',
        message: 'Is it have hooks?',
      },
    ]
    return inquirer
      .prompt(questions)
      .then(answers => {
        const { category, component_name, dir, have_props } = answers
        const path = `${category}/${ dir ? `${dir}/` : `` }${component_name}`
        const abs_path = `src/components/${path}`
        const type_annotate = have_props ? "React.FC<Props>" : 'React.FC'
        const props = have_props ? '(props)' : '()'
        const tag = args.tag ? args.tag : 'div'
        return { ...answers, path, abs_path, type_annotate, props, tag }
      })
  }
}
Component 모델뿐만 아니라 다양한 장소에서도 사용할 수 있다.

좋은 웹페이지 즐겨찾기