Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9309

コードジェネレーター、Hygen を導入する

$
0
0
Hygen とは CLIで実行できるコードジェネレーターです。 テンプレートを作成して、それをもとにファイルの生成などを行ってくれます。 新規ファイルの作成時、毎回同じ記述をする必要がなくなる、チームである程度ファイルの記載の仕方を揃えることが出来るなどといった利点があります。 カスタマイズ性、実行が高速であることがウリとされているようです。 この記事では、実際の導入手順と、とりあえず動かしてみるところまでを記載します。 導入 公式サイト だと、homebrew、npm でグローバルインストール、npx を利用したやり方が記載されてます。 チームで使うことを考えて、今回はリポジトリにdevDependencies として導入しようと思います。 yarn add -D hygen その後、init をしてあげる必要があります。 その際に二つの方法を選択せることができます。 repo: 他のリポジトリでテンプレートを作って、それを使い回す時に利用できます。 yarn run hygen init repo リポジトリ名 self: Hygen が自動でテンプレートを作成してくれます。最初はこっちで試してみるのが良さそうです。 yarn run hygen init self ルートディレクトリに、下記のようなファイルが生成されます。 _templates/ ├── generator │   ├── help │   │   └── index.ejs.t │   ├── new │   │   └── hello.ejs.t │   └── with-prompt │   ├── hello.ejs.t │   └── prompt.ejs.t └── init └── repo └── new-repo.ejs.t _templates/generator にはテンプレートを作成するために必要なファイルが生成されます(少しややこしいですが) help: new、with-prompt のコマンドの実行方法を出力してくれます $ yarn run hygen generator help yarn run v1.22.17 $ /workspaces/hygen-sample/node_modules/.bin/hygen generator help Loaded templates: _templates [object Function] help: hygen {bold generator new} --name [NAME] --action [ACTION] hygen {bold generator with-prompt} --name [NAME] --action [ACTION] Done in 0.84s. new: 新規のテンプレートを作成する with-prompt: 対話式の新規のテンプレートを作成する テンプレートからコード生成する 試しに一つテンプレートを作ってみます $ yarn run hygen generator new --name new_template --action hello yarn run v1.22.17 $ /workspaces/hygen-sample/node_modules/.bin/hygen generator new --name new_template --action hello Loaded templates: _templates added: _templates/new_template/hello/hello.ejs.t Done in 0.92s. _templates/new_template/hello/hello.ejs.t が生成されました。 _templates/new_template/hello/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) こちらはみた感じ、app/hello.js が作成されるようです。 テンプレートから、コードを生成するときは、yarn run hygen [name] [action] になります 今回は下記のようになります。 $ yarn run hygen new_template hello yarn run v1.22.17 $ /workspaces/hygen-sample/node_modules/.bin/hygen new_template hello Loaded templates: _templates added: app/hello.js Done in 0.92s. 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) テンプレート通りにファイルが作成されました! 終わりに 実際にテンプレートを変更したり、テンプレート用のリポジトリなど作ったりなど、いろいろ試して、また記事にしようと思います!

Viewing all articles
Browse latest Browse all 9309

Trending Articles