Load npm module in target project?


I’m working on a package to add debug code to source in the user’s project. This debug code (not my package code) requires an npm module. Is there a good way to make sure the user’s code will have that module required?

I already add a require statement to the top of the user’s source file but it would be convenient to also add the module to the users’ project automatically. I’m thinking of reading their package file and if it isn’t there then spawn a process to run mpn install xxx --save. Is there a better way?


Maybe --save-dev to put it in their devDependencies section?


Yes, --save-dev would be better. That way it will throw an error if they forget to remove the debug code. I guess there is no “cleaner” way to do this.

I seem to remember you could access the package.json file directly with a require. Can someone tell me how to do that? I tried require('package.json').


try with a path, not just a filename



You have to do it relative to the parent directory of the file being executed, to my recollection. So if the file is ./lib/foo.js and the package.json is in the root of the project, then it would be require('../package.json'), I believe.


That did it. Thx.