插件目的是将分离 app/extend/helper.js ,分成app/helper/*.js 的单个文件 egg-helper 自动读取 app/helper目录下的所有文件,并按照文件名为key的方式,挂在ctx.helper上,你可以直接使用 ctx.helper[filename][function]来使用,无需在文件中再次引入 优点:
- 不会覆盖egg原有的helper.js
- 自动读取helper目录下的所有文件,无需手动引入,并挂载在ctx.helper上
- 可以使用多级目录
链接:egg-helper
使用 // {app_root}/config/plugin.js exports.helper = { enable: true, package: 'egg-helper', };
示例 Add the util.js file to the app/helper folder
// app/helper/util.js
module.exports = app => {
return {
foo() {
// app is Application Object
console.log(app);
return 'hello helper';
},
};
};
如果想使用多级目录,例如:
// app/helper/util/util1.js
module.exports = app => {
return {
foo1() {
// app is Application Object
console.log(app);
return 'hello helper';
},
};
};
in Controller
DemoController extends Controller{
async index(){
this.ctx.helper.util.foo(); // 通过如下路径可以访问到方法
this.ctx.helper.util.util1.foo();// 如果是多级目录,也是通过文件名访问
}
}