Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional require in express?

I'm using the reload package in development.

It's saved under devDependancies in package.json.

In my app.js I have:

if (process.env.NODE_ENV !== 'production') {
    reload(server, app)
}

Heroku strips out all packages under devDependancies after building, and my import reload from 'reload' is throwing an error. I'm using babel to build it in production btw.

Heroku logs:

Error: Cannot find module 'reload'
2018-05-16T01:00:46.213772+00:00 app[web.1]:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
2018-05-16T01:00:46.213773+00:00 app[web.1]:     at Function.Module._load (internal/modules/cjs/loader.js:497:25)
2018-05-16T01:00:46.213776+00:00 app[web.1]:     at Module.require (internal/modules/cjs/loader.js:626:17)

I'm aware I can skip the "pruning" part, but would prefer to strip loading of reload module in production instead.

How do I conditionally import or require a package?

like image 269
hackerl33t Avatar asked May 16 '18 01:05

hackerl33t


1 Answers

The general rule is to put your import at the top, but you don't have to

if (process.env.NODE_ENV !== 'production') {
    require('reload')(server, app)
}

should work.

like image 142
generalhenry Avatar answered Sep 18 '22 14:09

generalhenry