When configuring multiple environments for a Loopback 4 Application, it can appear less straight forward than with Loopback 3, so here is a quick fix for how to get over this obstacle as elegantly as possible in 5 minutes.
- Import dotenv and create a .env file in the root of the app.
- Put your database configuration in this file.
- Empty the existing datasource file so it contains an empty JSON (file is required by compiler and the bootstrapping).
- Add the code below to the application.ts file in the src directory.
- Don’t forget to require the dotenv from the run command.
this.bind('datasources.default').to(new DefaultDataSource()); this.dataSource(new DefaultDataSource()); this.bind('datasources.config.default').to({ name: 'default', connector: 'mongodb', hostname: process.env.DB_DEFAULT_HOSTNAME, port: process.env.DB_DEFAULT_PORT, user: process.env.DB_DEFAULT_USER, password: process.env.DB_DEFAULT_PASSWORD, database: process.env.DB_DEFAULT_DATABASE, useNewUrlParser: process.env.DB_DEFAULT_USENEWURLPARSER, authSource: process.env.DB_DEFAULT_AUTHSOURCE }); this.bind('datasources.default').toClass(DefaultDataSource);
This is a quick fix intended to help move on if in a pickle, I will refine this further so the application will check the process.env.NODE_ENV variable instead and load the corresponding file.
For the original inspiration to this post, head over here: https://medium.com/p/8f085399268/responses/show