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 ie package.global.json
and install all of them globally?
And again, is there some sort of convention?
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.