Egg.js VS Thinkjs 简单分析使用
命令行脚手架
Egg.js
$ npm i egg-init -g
$ egg-init egg-example --type=simple
$ cd egg-example
$ npm i
$ npm run dev
打开浏览器访问 http://127.0.0.1:7001/
Thinkjs
$ npm install -g think-cli
$ thinkjs new demo;
$ cd demo;
$ npm install;
$ npm start;
打开浏览器访问 http://127.0.0.1:8360/
从创建项目的脚手架来看两者基本一致,但是think-cli 支持 使用命令行创建controller、service、model等
$ thinkjs controller <controller-name> [module-name]
$ thinkjs service <service-name> [module-name]
$ thinkjs model <model-name> [module-name]
更多使用方法查看https://github.com/thinkjs/think-cli
配置
Egg.js
-
默认配置在config文件夹下config.default.js
-
写法
module.exports = { keys:'my-cookie-secret-key', }; // 或 exports.keys = 'my-cookie-secret-key'; // 或 module.exports = appInfo => { return { keys: 'my-cookie-secret-key' }; };
-
支持多环境配置
-
多个配置文件会覆盖合并,框架在启动时会把合并后的最终配置 dump 到
run/application_config.json
(worker 进程)和run/agent_config.json
(agent 进程)
Thinkjs
-
根据不用功能划分不同配置文件
config.js
通用的一些配置adapter.js
adapter 配置router.js
自定义路由配置middleware.js
middlware 配置validator.js
数据校验配置extend.js
extend 配置
-
写法
module.exports = { keys:'my-cookie-secret-key', }; // 或 exports.keys = 'my-cookie-secret-key';
-
支持多环境配置
-
最终配置文件会合并,合并后的配置在
runtime/config/[env].json
中 -
支持动态设置配置
Koa内置对象
Egg.js和Thinkjs都用扩展Koa对象,app,request,response,context
Egg.js
启动自定义脚本获取
// app.js
module.exports = app => {
app.cache = new Cache();
};
controller 中使用 this.ctx.app
this.ctx
this.ctx.request
this.ctx.response
Thinkjs
任何地方使用think.app
controller 中使用 this.ctx
this.ctx.req
this.ctx.res
中间件
两者都是基于Koa实现的,中间件基于洋葱圈模型
两者写法一致
// middleware/log.js
const defaultOptions = {
consoleExecTime: true // 是否打印执行时间的配置
}
module.exports = (options = {
}) => {
// 合并传递进来的配置
options = Object.assign({
}, defaultOptions, options);
return (ctx, next) => {
if(!options.consoleExecTime) {
return next(); // 如果不需要打印执行时间,直接调用后续执行逻辑
}
const startTime = Date.now();
let err = null;
// 调用 next 统计后续执行逻辑的所有时间
return next().catch(e => {
err = e; // 这里先将错误保存在一个错误对象上,方便统计出错情况下的执行时间
}).then((