Modules and dependencies
Ru | En
A module in Drakon.Tech can call functions from other modules and libraries. An external object that a module can use is called a dependency.
How to add dependencies to a module
- Right-click on a module in the Projects tree and choose "Properties."
- Click the "Dependencies" button.
- Enter the dependencies, one per line. Each dependency will become a global object visible in all module functions.
For example, let's create three modules, mod1, mod2, and mod3.
- mod1 shall depend on modules mod2 and mod3.
- mod3 shall depend on mod1 (yes, circular dependencies are perfectly ok).
In the dependencies of module mod1, we write:
In the dependencies of module mod3, we write:
Note that the names of the dependencies are not the same as the module names. They can be the same, but that is not necessary. A module does not know which specific modules it depends on. Only the application that will use the modules knows the actual interconnection of the modules.
Module mod1 only knows that two global objects are available, foo and bar.
This is how we use the dependencies inside module mod1:
How to resolve module dependencies
- Create an application.
- Go to the "Modules" tab and add all the modules you need. Note that many applications can re-use the same module.
- Assign modules to dependencies.
- Choose the startup module. The startup module must have an exported function with the name main.
Our application will produce code like this:
var instanceOfMod1 = mod1(); // Create an instance of mod1 var instanceOfMod2 = mod2(); // Create an instance of mod2 var instanceOfMod3 = mod3(); // Create an instance of mod3 instanceOfMod1.foo = instanceOfMod2; // Point dependency foo to mod2 instanceOfMod1.bar = instanceOfMod3; // Point dependency bar to mod3 instanceOfMod3.moo = instanceOfMod1; // Point dependency moo to mod1 instanceOfMod1.main(); // Start up the app. The main() function must be present in mod1. // The main() function must have "export" flag set.
The whole point of an application is to produce such boilerplate code. It's a dependency injection tool.
How to use dependencies in a NodeJS app
Since a module does not know what its dependencies point to, we can connect its dependencies to anything. For example, we could link the dependencies to npm modules or other modules that do not come from Drakon.Tech.
In this example, the module helloexpress uses the Express framework.
In our NodeJS app:
const express = require('express'); const app = express(); const helloexpress = require('./helloexpress'); // Include helloexpress const hello = helloexpress(); // Create an instance of module helloexpress hello.app = app; // helloexpress module must have an "app" dependency for this to work. hello.startServer(); // We suppose helloexpress has an exported function startServer()
Inside helloexpress, there now is a global object app pointing to Express.