起因
因为工作中遇到了需要创建新的Koajs项目,但在Yeoman上找了一圈,发现使用的Koa的generator更新实在太少太慢,用的好多模块都太老,不是很适合。公司内部还处于Copy的模式,没有一个统一管理的基础项目。于是就想到了自己去弄个 yeoman generator。一是学习了新的东西,二来确实相当方便,新建工程爽爽的。所以说也不算是教程,只是自己成功搞定generator的思路,欢迎大家指教。
generator地址:generator-koa-sudiyi
题外话:Koa 比起 Express 实在好用太多。
账号准备
Your generator must have a GitHub repository description, the yeoman-generator keyword and a description in package.json to be listed.
下载安装yo和generator-generator
在已经有装好node和npm的前提下,需要全局安装yo
和generator-generator
npm install -g yo
npm install -g generator-generator
之后运行generator-generator
来创建我们自己需要的generator的基础框架
yo generator
在一系列设置问题之后
我们得到了generator的目录:
.
├── generators/
│ └── app/
│ ├── index.js
│ └── templates/
│ └── dummyfile.txt
├── .editorconfig
├── .gitattributes
├── .gitignore
├── .eslintrc
├── .travis.yml
├── .yo-rc.json
├── package.json
├── gulpfile.js
├── README.md
├── LICENSE
└── test/
└── app.js
开始行动
准备模版
首先我是准备了我将要生成基础工程的一些模版文件,放在 templates 文件夹中,删掉了默认生成的 dummyfile.txt。这是Yeoman默认的放模版文件的文件夹,当然你也可以通过templatePath
去设置其他文件夹。这里我就不弄复杂了,详情可以参考官网的API文档,欢迎一起探讨。
因为我需要的基础工程只是一个简单的koajs,并实现rest就行,所以需要建立的模版不是特别复杂,我就偷懒放在一个文件夹下了。(详细内容可以去我的Github Repo上去看)
编辑index.js
接下来开始编辑index.js文件,我们的generator如何生成什么样的基础工程,目录结构,是否自动安装依赖模块等等都是在这一步完成。先贴上代码,后面再把重要的地方重点说明。
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var extend = require('deep-extend');
var mkdirp = require('mkdirp');
module.exports = yeoman.generators.Base.extend({
initializing: function () {
this.props = {};
},
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the luminous ' + chalk.red('generator-koa-sudiyi') + ' generator!'
));
var prompts = [
{
type: 'input',
name: 'projectName',
message: 'Please input project name (sudiyi_app):',
default: 'sudiyi_app'
},
{
type: 'input',
name: 'projectDesc',
message: 'Please input project description:'
},
{
type: 'input',
name: 'projectMain',
message: 'Main file (app.js):',
default: 'app.js'
},
{
type: 'input',
name: 'projectAuthor',
message: 'Author (sudiyi):',
default: 'sudiyi'
},
{
type: 'list',
name: 'projectLicense',
message: 'Please choose license:',
choices: ['MIT', 'ISC', 'Apache-2.0', 'AGPL-3.0']
}
];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
defaults: function () {
if (path.basename(this.destinationPath()) !== this.props.projectName) {
this.log(
'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
'I\'ll automatically create this folder.'
);
mkdirp(this.props.projectName);
this.destinationRoot(this.destinationPath(this.props.projectName));
}
},
writing: function () {
var readmeTpl = _.template(this.fs.read(this.templatePath('README.md')));
this.fs.write(this.destinationPath('README.md'), readmeTpl({
generatorName: 'generator-koa-sudiyi',
yoName: 'koa-sudiyi'
}));
var pkg = this.fs.readJSON(this.templatePath('package_tmpl.json'), {});
extend(pkg, {
dependencies: {
'aliyun-sdk': '^1.6.3',
'bluebird': '^3.0.6',
'co': '^4.6.0',
'co-body': '^4.0.0',
'co-busboy': '^1.3.1',
'co-foreach': '^1.1.1',
'co-redis': '^2.0.0',
'co-request': '^1.0.0',
'co-views': '^0.2.0',
'cron': '^1.1.0',
'kcors': '^1.0.1',
'koa': '^1.1.2',
'koa-bodyparser': '^2.0.1',
'koa-compress': '^1.0.8',
'koa-jwt': '^1.1.1',
'koa-logger': '^1.3.0',
'koa-route': '^2.4.2',
'koa-router': '^5.3.0',
'koa-static': '^1.5.2',
'lodash': '^3.10.1',
'log4js': '^0.6.29',
'moment': '^2.10.6',
'node-uuid': '^1.4.7',
'nodemailer': '^1.10.0',
'redis': '^2.4.2',
'sequelize': '^3.14.2',
'sequelize-cli': '^2.2.1',
'socket.io': '^1.3.7',
'swig': '^1.4.2',
'thunkify-wrap': '^1.0.4',
'async': '^1.5.0',
'koa-body-parser': '^1.1.2',
'koa-generic-session': '^1.10.0',
'koa-redis': '^1.0.1',
'mysql': '^2.9.0',
'request': '^2.67.0'
},
devDependencies: {
'mocha': '^2.3.3',
'chai': '^3.4.1',
'gulp': '^3.9.0',
'faker': '^3.0.1',
'minimist': '^1.2.0',
'co-mocha': '^1.1.2'
}
});
pkg.keywords = pkg.keywords || [];
pkg.keywords.push('generator-koa-sudiyi');
pkg.name = this.props.projectName;
pkg.description = this.props.projectDesc;
pkg.main = this.props.projectMain;
pkg.author = this.props.projectAuthor;
pkg.license = this.props.projectLicense;
this.fs.writeJSON(this.destinationPath('package.json'), pkg);
mkdirp('lib/controllers');
mkdirp('lib/middlewares');
mkdirp('lib/middlewares/common');
mkdirp('lib/models');
mkdirp('lib/db');
mkdirp('lib/logger');
mkdirp('lib/routes');
mkdirp('lib/utils');
mkdirp('public');
this.fs.copy(
this.templatePath('gitignore_tmpl'),
this.destinationPath('.gitignore')
);
this.fs.copy(
this.templatePath('jshintrc_tmpl'),
this.destinationPath('.jshintrc')
);
this.fs.copy(
this.templatePath('app_tmpl.js'),
this.destinationPath('app.js')
);
this.fs.copy(
this.templatePath('index_tmpl.js'),
'lib/index.js'
);
this.fs.copy(
this.templatePath('request_id_tmpl.js'),
'lib/middlewares/common/request_id.js'
);
},
install: function () {
this.installDependencies({bower: false});
}
});
promoting块
var prompts = [...];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
我们需要通过问题的方式采集用户建立工程的数据。promts
是问题集合,在调用this.promt
使其在运行yo的时候提出来,最后将用户输入的数据存在this.props
中,以方便后面调用。
default
mkdirp(this.props.projectName);
this.destinationRoot(this.destinationPath(this.props.projectName));
mkdirp
是我们引用的模块,用来创建文件夹。this.destinationRoot
则是设置要创建的工程的根目录。
writing
使用_.template
(lodash的template功能)和this.fs.write
将模版中的关键字替换为用户的输入项。
this.fs.readJSON
和this.fs.writeJSON
,则是将package.json模版中的数据读取出来,作出一定修改写成新的文件。
最后使用mkdirp
和this.fs.copy
构建工程目录结构和将一些不要修改的配置文件copy到指定目录。
到此我们的代码工作就结束了,只剩最后发布啦~
发布
首先需要一个npm账号,如果没有可以使用npm adduser
创建;如果有则运行npm login
登陆。然后到工程根目录下,运行npm publish
就可以发布了。
因为npm的repo下载很慢,我们很多时候用的taobao的repo。所以发布的时候需要切回到npm的repo。
祝成功!
(全文完)