dwyl / learn-node-js-by-example

:cloud: Practical node.js examples.
http://nelsonic.gitbooks.io/node-js-by-example/
Other
48 stars 11 forks source link

Can/should I use/require node_modules included by my dependencies' node_modules? #28

Open nelsonic opened 8 years ago

nelsonic commented 8 years ago

Scenario:
Imagine you are building a web application using a framework such as hapi and you know that when you npm install hapi --save it installs several "utilities" in it's node_modules (e.g: boom, joi, hoek, etc.)

Question:
Can we avoid explicitly re-installing Joi in the project and use the module included in my_app/node_modules/hapi/node_modules/joi/lib/ e.g: in my server.js file:

var Hapi = require('hapi'); 
var Joi = require('./node_modules/hapi/node_modules/joi/lib/'); // good or bad idea? Why?

var server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
    method: 'GET',
    path: '/{name*}',
    config: {
        validate: {  // validate using Joi
          params: { 
            name: Joi.string().max(40).min(2).alphanum()
          } 
        },
        handler: function (req,reply) {
            reply('Hello '+ req.params.name + '!');
        }
    }
});

server.start(function() {
    console.log('Now Visit: http://localhost:3000/YOUR_NAME_HERE')
});

While the idea of not installing the same node_modules multiple times appears logical on the surface we would like to know the real world pitfalls of doing this? The clear advantage is that when you update your dependency on Hapi you will also get all the latest versions of its' dependencies the potential downside is that you won't know when there's a breaking change in one of those dependencies ... what else?

Note: I/we do not currently do this in any of our Node.js code, but someone asked me _why not?_ today and I did not have a comprehensive answer for them... "Because it's bad practice..." is not a good answer, we want to understand _why_... not have the 4 monkeys in a room "reason"


See: http://stackoverflow.com/questions/37237514/can-should-we-use-require-node-modules-included-by-my-dependencies-node-modules