Yeoman-脚手架搭建工具《二》

Prototype methods as actions

每个挂载到Generator prototype的方法都会被看成一个task。每一个task都会在Yeoman环境中按照顺序运行。换个简单的说法就是,object上经过Object.getPrototypeOf(Generator)返回的方法会自动执行。npm

Helper and private methods

有三个方式能够建立不自动执行的方法segmentfault

1.给函数名称加上_前缀(eg:_private_method)api

class extends Generator {
     method1() {//这个是一个task,会被自动运行
       console.log('hey 1');
     }

     _private_method() {//这个方法不会自动执行
       console.log('private hey');
     }
   }

2.用实例方法promise

class extends Generator {
     constructor(args, opts) {
       // Calling the super constructor is important so our generator is correctly set up
       super(args, opts)

       this.helperMethod = function () {//将方法挂载到this上
         console.log('won\'t be called automatically');
       };
     }
   }

3.扩展父generator异步

class MyBase extends Generator {
     helper() {
       console.log('methods on the parent generator won\'t be called automatically');
     }
   }

   module.exports = class extends MyBase {
     exec() {
       this.helper();
     }
   };

The run loop

若是只有一个generator,按顺序运行任务是能够的。但一旦你开始把他们组合在一块儿,这是不够的。async

run loop是一个优先级队列系统,优先级在代码中定义为特殊的原型方法名。当方法名与优先级名相同时,运行循环会将该方法推送到这个特殊队列中。若是方法名与优先级不匹配,则将其推送到默认组中。函数

class extends Generator {
  priorityName() {}
}

你也能够把多个方法组合起来工具

Generator.extend({
  priorityName: {
    method() {},
    method2() {}
  }
});

可用优先级为(按运行顺序):oop

1.initializing - 初始化方法 (checking current project state, getting configs, etc)


2.prompting - 提示用户交互 (where you’d call this.prompt())
configuring - Saving configurations and configure the project (creating .editorconfig files and other metadata files)

3.default - 执行不匹配其余的优先函数的函数

4.writing - Where you write the generator specific files (routes, controllers, etc)

5.conflicts - Where conflicts are handled (used internally)

6.install - Where installations are run (npm, bower)

7.end - Called last, cleanup, say good bye, etc

异步任务

有多种方法能够暂停运行循环,直到任务以异步方式完成工做。this

最简单的方式就是return a promise。当resolves执行的,loop能够继续执行。若是依赖的异步api不支持promise,能够调用this.async()。eg:

asyncTask() {
  var done = this.async();

  getUserEmail(function (err, name) {
    done(err);
  });
}

Yeoman-脚手架搭建工具《一》
Yeoman-脚手架搭建工具《三》

相关文章
相关标签/搜索