Configurations
Learning objectives
- You know the benefits of extracting configurations to separate files.
Similar to dependendencies, it is possible to also extract configurations to a separate location. This is especially useful when you have multiple configurations that you want to use in different parts of your application, or when you want to use the same configuration in multiple locations.
As an example, the Eta template engine is currently configured in each file that uses it. This is not ideal, as it is possible that you want to change the configuration in the future. One possible solution is to create a separate file that contains the configuration, and then import it in the files that need it.
Let's create a new file called etaConfig.js
and place it into a config
folder.
tree --dirsfirst
.
├── config
| └── etaConfig.js
├── controllers
│ ├── authController.js
│ ├── mainController.js
│ └── todoController.js
├── services
│ ├── sessionService.js
│ ├── todoService.js
│ └── userService.js
├── middlewares
│ └── middlewares.js
├── templates
│ ├── login.eta
│ ├── main.eta
│ ├── registration.eta
│ ├── todo.eta
│ └── todos.eta
├── app.js
├── app-run.js
└── deps.js
Now, we can import Eta to the etaConfig.js
file from deps.js
, and configure it there. Then, once Eta is configured, we can export it from the etaConfig.js
file for others to use.
import { Eta } from "../deps.js";
const eta = new Eta({ views: `${Deno.cwd()}/templates/` });
export { eta };
As an example, we could now change the todoController.js
to import eta
from etaConfig.js
. Now, we could use eta
without the explicit need to configure it there. With this change, the beginning of mainController.js
would look as follows, and we would not explicitly create an eta object there.
import { eta } from "../config/etaConfig.js";
import * as todoService from "./todoService.js";
// ...
This is a small change, but it makes the code more maintainable. If we want to change the configuration of Eta, we can do it in one place, and it will affect all the files that use it. As an example, if we would want to enable caching of the view templates, we could do it in the etaConfig.js
file.
import { Eta } from "../deps.js";
const eta = new Eta({ views: `${Deno.cwd()}/templates/`, cache: true });
export { eta };
Note that enabling cache in development leads to changes to view templates not being reflected on reload.