Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS import only if not in production

Tags:

node.js

Basically, I am using morgan to look at logs in developement. I have it under --save-dev. But in my app.js I use const morgan = require('morgan');. It runs fine on my local machine but I only use morgan depending on NODE_ENV. How can I make it that it doesnt raise a module not found exception in production? I will not be using it there so I have it in dev dependencies. Do I have to manually remove that line every time I deploy? Thanks :-)

like image 588
ICanKindOfCode Avatar asked Jan 18 '18 04:01

ICanKindOfCode


2 Answers

You can try something like:

if(NODE_ENV !== 'production') {
  const morgan = require('morgan');
  app.use(morgan(...))
}

I just wrote a similar code snippet and ran into no issues.

like image 197
therobinkim Avatar answered Nov 15 '22 23:11

therobinkim


You can just check the NODE_ENV environment variable in your code via the process.env object Node provides:

if(process.env.NODE_ENV !== 'production') const morgan = require('morgan');
like image 26
Jonny Asmar Avatar answered Nov 15 '22 21:11

Jonny Asmar