Egg: 有谁知道config文件里面的配置在service里面怎么读取?

Created on 1 Nov 2017  ·  13Comments  ·  Source: eggjs/egg

1,如何读取配置文件里的值?
2,为什么在service或者controller里面不能读取项目根目录下的文件?

need-more-information not follow template

Most helpful comment

@sansroman 通常情况下,你这个文件肯定是要在 egg 里面用的。所以思路是,你那个文件应该是 module.exports = app => {} 的方式,然后通过 loader 加载挂到 app 上

All 13 comments

  1. this.config 请阅读文档
  2. 提供详细信息.

应该要 this.app.config

按照 @atian25 的写法即可

第二个问题与 egg 无关,如果想引入,自己 require

有相关问题,怎么使用把配置的相关变量引用为某个文件的全局变量,必须用require引入config.default.js么

@sansroman 通常情况下,你这个文件肯定是要在 egg 里面用的。所以思路是,你那个文件应该是 module.exports = app => {} 的方式,然后通过 loader 加载挂到 app 上

比如我想在扩展中引用config中的常数,但是我无法访问app,我只能用上述方法通过访问app对象来获取config么,扩展的加载机制是怎样的,是不是我理解错了这个配置文件的含义,不应该把所有的配置信息放到这个里面

@sansroman 必然,刚才不是说了么,你扩展是可以拿到 app 的。

举个例子,这是一种实现方式

// {app_root}/lib/foo.js
module.exports = class Foo {
  constructor(app) {
    this.app = app;
  }
  sayHi() {}
}

// {app_root}/app/extend/application.js
const Foo = require('../../lib/foo');
const FOO = Symbol('Application#foo');
module.exports = {
  get foo() {
    // 缓存
    if (!this[FOO]) {
      // 初始化
      this[FOO] = new Foo(this);
    }
    return this[FOO];
  }
}

// 使用
this.app.foo.sayHi()

也可以通过 loader 方式:

// app.js
app.xx = app.loader.loadFile('path/to/file');
// 如果加载的文件是 app => {} 的方式则会自动执行,这样你就有 app 在构造函数了

。。。 楼上不要误导人,这个文件不要读取,直接 this.ctx.config,多看文档

我错了,多看文档

在自定义目录的场景下怎么获取 config 的配置呢

// app/db/index.ts
const DB = require('db-demo');
// 如何拿到 config 配置
DB.initialize(config.SecretKey, config.SafetyKey);
export default DB;
// app/module/index.js
import DB from '../db';

export const find = (id: string) => {
   return DB.find(id);
}

以上场景无法通过 service或者controller或 application 拿到上下文环境,如何获取 config 配置信息呢。

虽然最终 find 会在 service或者controller 下调用,但总不能一层层将 ctx.config 传递到 app/db 下做初始化吧

js 的话,不应该自己 require,而是如我上面示范的代码,通过 loader 来加载 app/db/index.ts

ts 的话,应该要通过注解的方式去实例化注入, cc @killagu

在可以访问到app的情况下,肯定可以知道怎么访问到config,现在大家的疑问是在一些自定义目录中,想访问到config配置,只能靠自己require('config.default.js') 么,楼上答非所问的一大堆。

https://github.com/atian25/egg-showcase/pull/13

通过 loader 去加载自定义目录即可。

Was this page helpful?
0 / 5 - 0 ratings