JSConfで@takepepeさんの話の中で出てきたhygen
が便利そうだったので調べてみた
hygen
はCLI からファイルを雛形出力してくれるツール
例えば、1つのReactコンポーネントをつくるときに、それと一緒に.stories.tsx
や.test.tsx
ファイルも必要になる
だいたいこれらのファイルのフォーマットは変わらないので、雛形を作って生成すると効率が向上する
hygen
は以下のコマンドで簡単に始めることができる
$ npx hygen init self Loaded templates: /Users/uggds/.npm/_npx/dac8989e9a8aaa66/node_modules/hygen/src/templates added: _templates/generator/help/index.ejs.t added: _templates/generator/with-prompt/hello.ejs.t added: _templates/generator/with-prompt/prompt.js added: _templates/generator/new/hello.ejs.t
実行すると以下のファイルが生成される
└── _templates └── generator ├── help │ └── index.ejs.t ├── new │ └── hello.ejs.t └── with-prompt ├── hello.ejs.t └── prompt.js
これらはgeneratorの各コマンド(help | new | with-prompt)に対応するファイルで、例えば$ npx hygen generator help
を実行すると
$ npx hygen generator help Loaded templates: _templates help: hygen generator new [NAME] --action [ACTION] hygen generator with-prompt [NAME] --action [ACTION]
となるが、これは_templates/generator/help/index.ejs.t
に記述されているものが出力されている
--- message: | hygen {bold generator new} --name [NAME] --action [ACTION] hygen {bold generator with-prompt} --name [NAME] --action [ACTION] ---
なので、new
コマンドに対しては_templates/generator/new
が関係しており、$ npx hygen generator new
とすると、_templates/generator/new/hello.ejs.t
の内容が処理される
--- to: app/hello.js --- const hello = `` Hello! This is your first hygen template. Learn what it can do here: https://github.com/jondot/hygen `` console.log(hello)
---
で囲まれた箇所がYAML Front-matterと同じようにメタデータを定義するセクションで、to:
は出力先のファイルパスとファイル名をしている
--- to: app/hello.js ---
これで$ npx hygen generator new
を実行すると、以下の内容のapp/hello.js
が生成される
const hello = `` Hello! This is your first hygen template. Learn what it can do here: https://github.com/jondot/hygen `` console.log(hello)
対話型 CLI
対話型 CLI で値を受け取り、それを変数としてテンプレート内で使うことができる
対話型 CLI で値を受け取りはprompt.jsで設定する
試しに_templates/generator/new/prompt.js
を作成してみる
module.exports = [ { type: 'select', name: 'category', message: 'Choose directory.', choices: ['common', 'features', 'pages'], }, { type: 'input', name: 'name', message: 'What is the name of component?', validate: (input) => input !== '', }, ]
これで、再び$ npx hygen generator new
を実行すると対話形式になる
$ npx hygen generator new ? Choose directory. … ❯ common features pages
$ npx hygen generator new ✔ Choose directory. · common ? What is the name of component? ›
$ npx hygen generator new ✔ Choose directory. · common ? What is the name of component? › button
$ npx hygen generator new ✔ Choose directory. · common ✔ What is the name of component? · button Loaded templates: _templates added: common/button.js
無事common/button.js
が生成された
上の質問の回答によって下の質問が変わる場合も対応できるみたいで柔軟に使えそう
https://panda-program.com/posts/hygen-react
プロジェクトで使っていきたい
参考
https://zenn.dev/takepepe/articles/hygen-template-generator
https://www.hygen.io/docs/generators#advanced-interactive-prompt