Load npm module in target project?


#1

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?


#2

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


#3

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').


#4

try with a path, not just a filename

require('./package.json')


#5

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.


#6

That did it. Thx.