I'm working on a Node/Express project. Most of the code is contained in files that are inside folders, so that a folder named 'controllers' contains all of the project's controllers, a folder named 'services' contains all of the project's services etc. The code that starts the server is inside a file called app.js which is directly in the project root.
All controllers and services are declared as JS classes and contain a constructor. Dotenv is loaded inside app.js and env variables work nicely everywhere BUT inside class constructors, as those seem to be loaded before dotenv is initialized.
An example of the class syntax used:
export default class exampleService {
constructor() {
console.log('This is not working', process.env.EXAMPLE); // process.env.EXAMPLE is undefined
}
myFunction() {
console.log('This works just fine', process.env.EXAMPLE); // process.env.EXAMPLE is exactly how it's defined in .env
}
// All other class methods are here.
}
Is there a way I could get dotenv variables to work inside class constructors without having to import and init dotenv in the beginning of each class file?
If I do resort to importing dotenv individually to each class file, will it have any other cons besides making the code less clean?