Skip to content

Put all the files in the app/helper file directory into helper.js and hang them on the ctx.helper instance.

License

Notifications You must be signed in to change notification settings

yuezm/egg-helper

Repository files navigation

egg-helper

NPM version build status Test coverage David deps Known Vulnerabilities npm download

依赖说明

依赖的 egg 版本

egg-helper 版本 egg 1.x
1.x 😁
0.x

依赖的插件

开启插件

// config/plugin.js
exports.helper = {
  enable: true,
  package: 'egg-helper',
};

使用场景

在egg项目中,拆分工具函数,对工具函数单独维护

优势

  • 插件目的是分离 app/extend/helper.js ,分成app/helper/**/*.js 的单个文件,便于维护
  • 插件自动读取app/helper/**/文件目录下所有文件,并挂载到ctx.helper
  • 插件不会覆盖 app/extend/helper.js

如何使用

创建工具函数

// app/helper/util.js
module.exports = app => {
  return {
    foo() {
      // app is Application的实例
      return 'hello helper';
    },
  };
};

如果你想使用多级目录,如下所示

//app/helper/util/util1.js
module.exports = app => {
  return {
    foo1() {
      // app is Application的实例
      console.log(app);
      return 'hello helper';
    },
  };
};

使用工具函数

在Controller或Service中可以如下使用

DemoController extends Controller{
  async index(){
    this.ctx.helper.util.foo(); // 通过如下路径可以访问到你的方法
    this.ctx.helper.util.util1.foo1(); // 当你使用多级目录的时候,也是通过文件名来使用
  }
}

详细配置

请到 config/config.default.js 查看详细配置项说明。

单元测试

npm run test

提问交流

请到 egg issues 异步交流。

License

MIT

About

Put all the files in the app/helper file directory into helper.js and hang them on the ctx.helper instance.

Resources

License

Stars

Watchers

Forks

Packages

No packages published