首先什么是hygen?
hygen 是一个用于从模板文件生成样板的库。
前提
hygen 允许您在运行时指定选项。
您可以使用此选项更改模板文件中的处理,或者如果指定了某个选项,则跳过模板文件。
选项值可以在模板文件中处理,如果文件数量少,即使有类似的处理,也没什么大不了的,但如果文件数量增加,则统一优先处理。我开始想要了。
index.js 文件中的预处理
这些选项可以在将它们传递给每个模板文件之前组织在 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.ts代替index.js,但是因为看不懂提示类型定义所以放弃了。后悔...
有时间我想再试一次。
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308630870.html