I want to be able to send logs to the console, but only in development mode.
One can easily obtain this result using a combination of singleton pattern and IFEE.
utils/env.js
class Env {
active;
instance;
constructor() {
this.active = process.env.NODE_ENV === 'development';
}
static getInstance() {
if (!Env.instance) Env.instance = new Env();
return this.instance;
}
log(message) {
if (!this.active) return;
console.log(message);
}
}
The getInstance
method is static. Therefore it will be possible to use it directly on the class (rather than on the instance generated on the basis of it).
What this does is check if the class has already been instantiated. If not, it initializes the class itself in the instance
property. In both cases, it returns that instance. On which it will be possible to use other methods (in this case only log
).
This is what we call a Singleton. Something that, once instantiated, always returns the same instance.
The purpose of this class is to perform an action (console.log), only if under development. There is no need to instantiate a new object every time. Indeed, the use of the Singleton solution leads to a better performance and optimization of the memory space.
constructor() {
this.active = process.env.NODE_ENV === 'development';
}
The constructor is in charge of activating the class or not. The activation depends, in fact, on process.env.NODE_ENV
. The active
property, which contains the value true
in the case of development environment, is discriminating in the guard placed at the beginning of each method.
log(message) {
if (!this.active) return;
console.log(message);
}
Thus, it is possible to export the class. When imported into another file just use the getInstance method.
import Env from 'path/to/singleton';
const env = Env.getInstance();
env.log('I should work only in dev env');
However, using an IFEE can lead to slightly cleaner code. Instead of exporting the class, the IFEE is exported - or rather, the result of it.
utils/env.js
class Env {
...
}
export default (function () {
return Env.getInstance();
})();
Consequently, in any other file:
src/anyFile.js
import env from '../../utils/logger';
env.log('fresh & clean!');
This, of course, will be visible only when using npm start
. Serving the result of npm run build
will not output the log in console.
Useful resources:
Contacts:
Top comments (0)