title: Loader

The most important of Egg enhance Koa is Egg based on a certain agreement, code will be placed in different directories according to the functional differences, it significantly reduce development costs. Loader supports this set of conventions and abstracts that many low-level APIs could be extended.

Application, Framework and Plugin

Egg is a low-level framework, applications could use it directly, but Egg only has a little default plugins, applications need to configure plugins to extend features, such as MySQL.

  1. // application configuration
  2. // package.json
  3. {
  4. "dependencies": {
  5. "egg": "^2.0.0",
  6. "egg-mysql": "^3.0.0"
  7. }
  8. }
  9. // config/plugin.js
  10. module.exports = {
  11. mysql: {
  12. enable: true,
  13. package: 'egg-mysql',
  14. },
  15. }

With the increase number of applications, we find most of them have similar configurations, then we could extend a new framework based on Egg, which make the application configuration simpler.

  1. // framework configuration
  2. // package.json
  3. {
  4. "name": "framework1",
  5. "version": "1.0.0",
  6. "dependencies": {
  7. "egg-mysql": "^3.0.0",
  8. "egg-view-nunjucks": "^2.0.0"
  9. }
  10. }
  11. // config/plugin.js
  12. module.exports = {
  13. mysql: {
  14. enable: false,
  15. package: 'egg-mysql',
  16. },
  17. view: {
  18. enable: false,
  19. package: 'egg-view-nunjucks',
  20. }
  21. }
  22. // application configuration
  23. // package.json
  24. {
  25. "dependencies": {
  26. "framework1": "^1.0.0",
  27. }
  28. }
  29. // config/plugin.js
  30. module.exports = {
  31. // enable plugins
  32. mysql: true,
  33. view: true,
  34. }

From the above scene we can see the relationship of application, plugin and framework.

  • We implement business logics in application, we need to specify a framework to run, we could configure plugin to meet a special scene feature (such as MySQL).
  • Plugin only performs specific function, when two separate functions are interdependent, they still need to be separated into two plugins, and requires configuration.
  • Framework is a launcher (default is Egg), which is indispensable to run. Framework is also a wrapper, it aggregates plugins to provide functions unitedly, framework can also configure plugins.
  • We can extend a new framework based on framework, which means that framework can be inherited infinitely, like class inheritance.
  1. +-----------------------------------+--------+
  2. | app1, app2, app3, app4 | |
  3. +-----+--------------+--------------+ |
  4. | | | framework3 | |
  5. + | framework1 +--------------+ plugin |
  6. | | | framework2 | |
  7. + +--------------+--------------+ |
  8. | Egg | |
  9. +-----------------------------------+--------|
  10. | Koa |
  11. +-----------------------------------+--------+

loadUnit

Egg regard application, framework and plugin as loadUnit, because they are similar in code structure, here is the directory structure

  1. loadUnit
  2. ├── package.json
  3. ├── app.js
  4. ├── agent.js
  5. ├── app
  6. ├── extend
  7. | ├── helper.js
  8. | ├── request.js
  9. | ├── response.js
  10. | ├── context.js
  11. | ├── application.js
  12. | └── agent.js
  13. ├── service
  14. ├── middleware
  15. └── router.js
  16. └── config
  17. ├── config.default.js
  18. ├── config.prod.js
  19. ├── config.test.js
  20. ├── config.local.js
  21. └── config.unittest.js

However, there are still some differences

File Application Framework Plugin
app/router.js ✔︎
app/controller ✔︎
app/middleware ✔︎ ✔︎ ✔︎
app/service ✔︎ ✔︎ ✔︎
app/extend ✔︎ ✔︎ ✔︎
app.js ✔︎ ✔︎ ✔︎
agent.js ✔︎ ✔︎ ✔︎
config/config.{env}.js ✔︎ ✔︎ ✔︎
config/plugin.js ✔︎ ✔︎
package.json ✔︎ ✔︎ ✔︎

During the loading process, Egg will traverse all loadUnits to load the above files (application, framework and plugin are different), the loading process has priority.

  • follow the order Plugin => Framework => Application to load
  • The order of loading plugins depends on the dependencies, depended plugins will be loaded first, no dependencies plugins are loaded by the object key configuration order, see Plugin for details.
  • Frameworks are loaded by the order of inheritance, the lower the more priority.

For example, an application is configured with the following dependencies

  1. app
  2. | ├── plugin2 (depends plugin3)
  3. | └── plugin3
  4. └── framework1
  5. | └── plugin1
  6. └── egg

The final loading order is

  1. => plugin1
  2. => plugin3
  3. => plugin2
  4. => egg
  5. => framework1
  6. => app

The plugin1 is framework1 depended plugin, the object key order of plugin1 after configuration merger is prior to plugin2/plugin3. Because of the dependencies between plugin2 and plugin3, the order is swapped. The framework1 inherits the Egg, so the order it after the egg. The application is the last to be loaded.

See Loader.getLoadUnits method for details.

File order

The above lists default loading files, Egg will load files by the following order, each file or directory will be loaded according to loadUnit order (application, framework and plugin are different).

  • Loading plugin, find application and framework, loading config/plugin.js
  • Loading config, traverse loadUnit to load config/config.{env}.js
  • Loading extend, traverse loadUnit to load app/extend/xx.js
  • Application startup configuration, traverse loadUnit to load app.js and agent.js
  • Loading service, traverse loadUnit to load app/service directory
  • Loading middleware, traverse loadUnit to load app/middleware directory
  • Loading controller, loading application’s app/controller directory
  • Loading router, loading application’s app/router.js

Note

  • Same name will be override in loading, for example, if we want to override ctx.ip we could define ip in application’s app/extend/context.js directly.
  • See framework development for detail application launch order.

Loading File rules

The framework will convert file names when loading files, because there is a difference between the file naming style and the API style. We recommend that files use underscores, while APIs use lower camel case. For examplem app/service/user_info.js will be converted to app.service.userInfo.

The framework also supports hyphens and camel case.

  • app/service/user-info.js => app.service.userInfo
  • app/service/userInfo.js => app.service.userInfo

Loader also provides caseStyle to force the first letter case, such as make the first letter of the API upper case when loading the model, app/model/user.js => app.model.User, we can set caseStyle: 'upper'.

Extend Loader

Loader is a base class and provides some built-in methods based on the rules of the file loading, but itself does not call them in most cases, inherited classes call those methods.

  • loadPlugin()
  • loadConfig()
  • loadAgentExtend()
  • loadApplicationExtend()
  • loadRequestExtend()
  • loadResponseExtend()
  • loadContextExtend()
  • loadHelperExtend()
  • loadCustomAgent()
  • loadCustomApp()
  • loadService()
  • loadMiddleware()
  • loadController()
  • loadRouter()

Egg implements AppWorkerLoader and AgentWorkerLoader based on the Loader, inherited frameworks could make extensions based on these two classes, and Extensions of the Loader can only be done in the framework.

  1. // custom AppWorkerLoader
  2. // lib/framework.js
  3. const path = require('path');
  4. const egg = require('egg');
  5. const EGG_PATH = Symbol.for('egg#eggPath');
  6. class YadanAppWorkerLoader extends egg.AppWorkerLoader {
  7. constructor(opt) {
  8. super(opt);
  9. // custom initialization
  10. }
  11. loadConfig() {
  12. super.loadConfig();
  13. // process config
  14. }
  15. load() {
  16. super.load();
  17. // custom loading other directories
  18. // or processing loaded files
  19. }
  20. }
  21. class Application extends egg.Application {
  22. get [EGG_PATH]() {
  23. return path.dirname(__dirname);
  24. }
  25. // override Egg's Loader, use this Loader when launching
  26. get [EGG_LOADER]() {
  27. return YadanAppWorkerLoader;
  28. }
  29. }
  30. module.exports = Object.assign(egg, {
  31. Application,
  32. // custom Loader also need export, inherited framework make extensions based on it
  33. AppWorkerLoader: YadanAppWorkerLoader,
  34. });

It’s convenient for development team to customize loading via the Loader supported APIs. such as this.model.xx, app/extend/filter.js and so on.

The above is just a description of the Loader wording, see Framework Development for details.

Loader API

Loader also supports some low level APIs to simplify code when extending, here are all APIs.

loadFile

Used to load a file, such as loading app.js is using this method.

  1. // app/xx.js
  2. module.exports = app => {
  3. console.log(app.config);
  4. };
  5. // app.js
  6. // app/xx.js, as an example, we could load this file in app.js
  7. const path = require('path');
  8. module.exports = app => {
  9. app.loader.loadFile(path.join(app.config.baseDir, 'app/xx.js'));
  10. };

If the file export a function, then the function will be called with app as a parameter, otherwise using this value directly.

loadToApp

Used to load files from a directory into the app, such as app/controller/home.js to app.controller.home.

  1. // app.js
  2. // The following is just an example, using loadController to load controller in practice
  3. module.exports = app => {
  4. const directory = path.join(app.config.baseDir, 'app/controller');
  5. app.loader.loadToApp(directory, 'controller');
  6. };

The method has three parameters loadToApp(directory, property, LoaderOptions)

  1. directory could be String or Array, Loader will load files in those directories.
  2. property is app’s property.
  3. LoaderOptions are some configurations.

loadToContext

The difference between loadToApp and loadToContext is that loadToContext loading files into ctx instead of app, and it is lazy loading. Putting files into a temp object when loading, and instantiate object when calling ctx API.

For example, service loading is this mode

  1. // The following is just an example, using loadService in practice
  2. // app/service/user.js
  3. const Service = require('egg').Service;
  4. class UserService extends Service {
  5. }
  6. module.exports = UserService;
  7. // app.js
  8. // get all loadUnit
  9. const servicePaths = app.loader.getLoadUnits().map(unit => path.join(unit.path, 'app/service'));
  10. app.loader.loadToContext(servicePaths, 'service', {
  11. // service needs to inherit app.Service, so needs app as parameter
  12. // enable call will return UserService when loading
  13. call: true,
  14. // loading file into app.serviceClasses
  15. fieldClass: 'serviceClasses',
  16. });

app.serviceClasses.user becomes UserService after file loading, instantiating UserService when calling ctx.service.user.
So this class will only be instantiated when first calling, and will be cached after instantiation, multiple calling same request will only instantiating once.

LoaderOptions

ignore [String]

ignore could ignore some files, supports glob, the default is empty

  1. app.loader.loadToApp(directory, 'controller', {
  2. // ignore files in app/controller/util
  3. ignore: 'util/**',
  4. });

initializer [Function]

Processing each file exported values, the default is empty.

  1. // app/model/user.js
  2. module.exports = class User {
  3. constructor(app, path) {}
  4. }
  5. // Loading from app/model, could do some initializations when loading.
  6. const directory = path.join(app.config.baseDir, 'app/model');
  7. app.loader.loadToApp(directory, 'model', {
  8. initializer(model, opt) {
  9. // The first parameter is export's object
  10. // The second parameter is an object that only contains current file path.
  11. return new model(app, opt.path);
  12. },
  13. });

caseStyle [String]

File conversion rules, could be camel, upper, lower, the default is camel.

All three convert file name to camel case, but deal with the initials differently.

  • camel: initials unchanged.
  • upper: initials upper case.
  • lower: initials lower case.

Loading different files using different configurations.

File Configuration
app/controller lower
app/middleware lower
app/service lower

override [Boolean]

Overriding or throwing exception when encounter existing files, the default is false

For example, the app/service/user.js is both loaded by the application and the plugin, if the setting is true, the application will override the plugin, otherwise an error will be throwed when loading.

Loading different files using different configurations.

File Configuration
app/controller true
app/middleware false
app/service false

call [Boolean]

Calling when export’s object is function, and get the return value, the default is true

Loading different files using different configurations.

File Configuration
app/controller true
app/middleware false
app/service true