Question

When writing node.js apps, almost always you have to deal not only with local dependencies but also global packages required for the app. What is the best and common way to deal with that? I've seen it's possible to run npm in preinstall phase

"scripts": {
   "preinstall": "npm i -g grunt-cli"
}

It is strange though to run npm install from within npm script itself, but I guess that works.

However, is not very convenient if it's required to install several packages. Is it possible to tell npm to take all listed packages from another file i.e. package.global.json and install all of them globally?

And again, is there some sort of convention?

Was it helpful?

Solution

I consider requiring global modules for your build process to be a code smell. They work fine, but they fight against npm because they can't be added directly as dependencies. Instead, to use a package that includes a bin script to execute, I would recommend using the scripts field in package.json to provide a set of commands.

For example:

"dependencies": {
    "grunt-cli": "..."
},
"scripts": {
    "start": "grunt server",
    "test": "grunt test"
}

When you run npm start, npm will automatically add the location of the grunt-cli module into the PATH, and execute the grunt command to start the server, and running npm test will call through to the grunt test runner. This also means you have a really nice place for people to look to immediately know which commands are available to them, and it helps with consistency across the community. Note, start and test are special names in npm, so for other arbitrary commands, you need to run npm run-script <scriptname>

Generally I'd follow the pattern that if it is critical for the building and running of your module, do not require global modules, but use them to support enhanced workflows if needed. The main thing here is that I would list the absolutely critical scripts. There is nothing wrong with optionally using global modules. For instance, you may have a ton of grunt commands and you can't list every permutation in the package.json and that is fine. For your machine, you can globally install grunt-cli so you can run all of the commands exposed by the Gruntfile.

OTHER TIPS

Forcible global install is not really a good idea. You can just install these packages locally. Global scripts will be available in node_modules/.bin folder, and also in npm scripts this folder will be added to path, so one can just npm run grunt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top