yoman 创建generator

时间:2023-03-10 02:49:14
yoman 创建generator

yoman作为一个模板工具,能够创建自己的模板,下面具体介绍下。

首先 安装一个模板工具(npm install -g generator-generator),此工具会自动创建一些必要的文件。安装完成后,yo generator 就行。

最重要的一个文件就是generators中的index.js,生成器的所有逻辑都在此文件中。

文件里面的日志输出,同一用this.log("");

constructor

在此构造函数里,通常用来定义命令行的参数。一般用不到,通过prompt交互更加友好。

// Next, add your custom code

    this.option('coffee'); // This method adds support for a `--coffee` flag   这样就添加了一个coffee 命令行参数。

prompting

用来和client交互,控制台的输出:

this.log(yosay(
'Welcome to the magnificent ' + chalk.red('generator-ryanfirst') + ' generator!'
));
会在界面上显示:

yoman 创建generator

prompting是个对象可以定义多个交互方法:

   prompting:{
dir: function () { if (this.options.createDirectory !== undefined) {
return true;
}
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the magnificent ' + chalk.red('generator-ryanfirst') + ' generator!'
)); var prompt = [{
type: 'confirm',
name: 'createDirectory',
message: 'Would you like to create a new directory for your project?'
}]; return this.prompt(prompt).then(function (response) {
this.options.createDirectory = response.createDirectory;
}.bind(this));
},
dirname: function () {
if (!this.options.createDirectory || this.options.dirname) {
return true;
} var prompt = [{
type: 'input',
name: 'dirname',
message: 'Enter directory name'
}]; return this.prompt(prompt).then(function (response) {
this.options.dirname = response.dirname;
}.bind(this));
}
}

这样就会有以下的输出

yoman 创建generator

writing

主要的执行逻辑,创建文件和同步模板文件等。作为示例,仅仅做文件的同步:

  if(this.options.createDirectory){
this.destinationRoot(this.options.dirname);
this.appname = this.options.dirname;
}
this.fs.copy(
this.templatePath('.'), this.destinationPath('.')
);

如上,首先根据promt中的输入,创建文件夹,然后再同步所有的模板文件中的文件。

install

安装所有的依赖项。

以上即是所有的主要方法,可自定义方法,输出需要信息。yoman的执行顺序是依次从上到下执行。