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((
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值