@Debug() decorator for Angular and Node.js
Debugging is very important task of software development process. However many times we forget to remove debugging related code before deploying in production environment.
In this story, I will introduce a new @Debug() decorator which can be used in Angular and Node.js with TypeScript projects.
Angular client
In Angular, we can use environment.production
variable defined inside environment.ts
and environment.prod.ts
file. If you build your application using ng build
command then it will be built in development mode and environment.production
will be false
. If you build it with ng build --prod
command then it will be true
.
So you can write debug code as below. Here sayBye()
function will be called only in development mode. As soon as you build your application in production mode, this function will not get called.
@Debug() decorator
I have published a new decorator called @Debug() which we can apply on Angular application methods marking them for development purpose only. In below code, sayHi()
method has @Debug
decorator applied.
Usage
- Install
ng-debug-decorator
npm package by running below command in your Angular application
npm i --save-dev ng-debug-decorator
- Provide environment information to
@SetupEnvironment(environment)
decorator onngOnInit()
function ofapp.component.ts
component.
Apply `@Debug()`
decorator on Component/Service/(any TypeScript class) method(s)
- Build application in development mode by running command
ng build
. - Navigate to
dist
folder and run website using any web server e.g.lite-server
. - You should see method being executed with @Debug() decorator
- Now, build applicatiojs n using
ng build --prod
command - Navigate to
dist
folder and run website using any web server e.g.`lite-server`
. - Now you should not see output of method(s) on which
@Debug()
decorator is applied.
Here is the Angular client example repository:
Node.js client:
You can use @Debug() decorator in Node.js application with TypeScript support as well.
You can specify environment for Node.js application by setting up process.env.NODE_ENV
variable value. To run application in specific environment, you can execute command NODE_ENV=production node .
for production or NODE_ENV=development node .
for development environment.
Usage
- Install
ng-debug-decorator
npm package by running below command in your Nod.ejs application
npm i ng-debug-decorator
- Import
Debug()
function fromng-debug-decorator
package
import { Debug } from "ng-debug-decorator";
- Apply
@Debug()
decorator on class method’s
- Update
package.json
for specifying environment settings
"scripts": { "start": "NODE_ENV=development node ."}
- Run application by executing command
npm run start
.
If you are in production
environment then all methods with @Debug()
method won’t get executed at runtime.
You can find source code for Node.js client in below repository.