编写自己的yeoman generator

在构建前端项目时,使用yeoman generator可以帮助我们完成新建文件、安装模块、类库等重复性操作,然而已有的generator有时并不能满足需求,所以可以利用yeoman 的API来构建自己的生成器。

这里介绍自定义generator的大致步骤。

1. $ npm install -g generator-generator

2. $ yo generator

输入你的github用户名、生成器的名字(注意命名,yoeman会为你输入的名字添加前缀generator)



看一下生成的文件目录结构:



3. 编写generator

我们需要编写的文件主要是 app/index.js ,看下index文件的内容:

'use strict';
var util = require('util');
...

var MygeneratorGenerator = yeoman.generators.Base.extend({
  init: function () {
    // 初始化模块
    ...
  },

  askFor: function () {
    ...
  },

  app: function () {
    ...
  },

  projectfiles: function () {
    ...
  }
});

module.exports = MygeneratorGenerator;

这里省略了函数体,这样可以清楚的看到文件结构。

编写这个index.js时有几处需要注意的地方:

* 继承 yeoman.generators.Base

* 执行yo mygenerator 时模块中的所有方法会依次执行(即 init(), aksFor(), app(), projectfiles()顺次),如果需要加入私有方法(供其他方法调用)有多种方式,个人感觉比较方便的是直接在方法名之前添加下划线,如 

_protectedMethod: function() {
     console.log('This is a protected function.');
}


还是以一个简单的示例介绍几个基本的API。示例generator实现的效果:生成一个配置好gulp的livereload功能的项目。

index.js文件完整代码

'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');


var MygeneratorGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');
    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // 建议使用this.log() 而不是console.log, 因为在非命令行环境下console.log()不会显示
    this.log(yosay('Hi Keith, this is a new generator!'));
    var prompts = [{
      type: 'confirm',
      name: 'someOption',
      message: 'Hello boy, would you like to enable this option?',
      default: true
    }];

    this.prompt(prompts, function (props) {
      this.someOption = props.someOption;

      done();
    }.bind(this));
  },

  app: function () {
    //创建目录
    this.mkdir('app');
    this.mkdir('app/templates');

    // this.copy() 第一个参数为源文件名,默认目录为app/templates, 第二个参数为目标文件
    this.copy('index.html', 'app/index.html');  
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
  },

  gulp: function() {
    var done = this.async();

    // 安装gulp模块, this.npmInstall()会解决模块安装问题,对同一模块只安装一次
    this.npmInstall(['gulp', 'gulp-connect'], { 'saveDev': true }, done);
    this.template('gulpfile.js');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
  }
});

module.exports = MygeneratorGenerator;

index.js中的app方法中执行了copy函数,所以我们要在相应的目录(app/templates)下建立所需源文件,在app/templates 新建index.html。

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello yeoman</title>
</head>
<body>
  <h1>Hello World</h1>  
  <h2> This is my own yeoman generator!</h2>
</body>
</html>

在index.js中的gulp方法中还使用到了this.template方法,同样需要在app/templates目录下建立一个模板文件 gulpfils.js

gulpfile.js(这里对文件内容不做详细介绍)

'use strict';

var gulp = require('gulp'),
    connect = require('gulp-connect');

gulp.task('default', ['clean'], function () {
    gulp.start('start');
});

gulp.task('server', function() {
  connect.server({
    root: 'app',
    livereload: true
  });

  gulp.watch(['app/*.html'], ['html']);
});

gulp.task('html', function() {
  gulp.src('app/*.html')
    .pipe(connect.reload());
});

gulp.task('start', function() {
    console.log('This is default task, Developing...');
});

gulp.task('clean', function() {
  console.log('cleaning...');
});

此时,一个基本的generator就已经编写完毕。


4. 使用generator

写好generator后可以将它发布到npm中,这里先在本地使用,在generator根目录下执行

$ npm link

接下来就和使用其他yeoman generator一样了,在任意工作目录下执行

$ yo mygenerator

等待安装完毕,cd到新建项目的根目录下,使用livereload功能(修改html文件保存后浏览器自动刷新),执行

$ gulp server

访问 http://localhost:8080即可


到此一个基本的generator构建加使用过程就已经结束,关于自定义generator的更多API请参考官方文档http://yeoman.github.io/generator/


构建generator官方教程http://yeoman.io/authoring/getting-started.html













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值