そもそもhygenって何
hygenはテンプレートファイルからボイラープレートを生成するためのライブラリです。
前提
hygenでは実行時にオプションを指定できます。
このオプションによってテンプレートファイル内の処理を変えたり、あるオプションが指定されていたらテンプレートファイルをスキップしたりするみたいなことができます。
オプションの値はテンプレートファイル内で処理できますし、ファイル数が少ない場合は同じような処理があっても大した手間では無いですが、ファイル数が多くなってくると一律で最初に処理しておきたくなってきました。
index.jsファイルで前処理
これらのオプションは各テンプレートファイルに渡す前にindex.jsファイルで整理することができます。
module.exports = {
prompt: ({ prompter, args }) => {
const prompts = [];
!args.path &&
prompts.push({
type: 'input',
name: 'path',
message:
'パス(~~/以降)を入力してください。ex.) foo/_slug@string/bar',
});
!args.auth &&
prompts.push({
type: 'select',
name: 'auth',
message:
'タイプを選択してください。',
choices: [TYPE.FOO, TYPE.BAR, TYPE.BUZZ],
});
args.get &&
!args.option &&
args.option !== 'false' &&
prompts.push({
type: 'confirm',
name: 'option',
message: 'オプションを定義しますか?',
});
return prompter.prompt(prompts).then((res) => {
const merged = {
get: null,
post: null,
put: null,
del: null,
...args,
...res,
};
return {
...merged,
hasOption: merged.option && merged.option !== 'false',
hasPathParam: merged.path.indexOf('@') !== -1,
withAuth: merged.auth !== TYPE.BUZZ,
hasMethod:
!!merged.get || !!merged.post || !!merged.put || !!merged.del,
overwrite: !!merged.overwrite,
};
});
},
};
例えばオプションAが指定されている時はオプションBを無視したりとか、オプションAとオプションBの値を組み合わせてオプションCの値を作ったりとかできます。
その他、必須入力にしたいオプションが指定されていない場合はプロンプトで入力を促したりもできます。
これで複雑な設定があっても各テンプレートファイルが汚れないようにできますね。
余談
index.tsが使える
index.jsの代わりにindex.tsが使えるようなのですがpromptの型定義がよくわからなくて断念しました。無念…
時間ができたら再チャレンジしてみたいと思います。