通过 package.json 安装“ global”npm 依赖项

我有一些“全局”依赖项(jshint、 csslint、 buster 等)当我的软件包通过 npm install安装时,我希望能够通过命令行自动安装和执行。这可能吗?

目前,我正在手动执行以下操作:

  1. npm install -g <package_name>
  2. 从我的项目: npm link <package_name>

更新: 刚刚遇到了用于 npm 的 这个功能要求。似乎 Package.json 中的 scripts配置是正确的选择?

再次更新: 或者,在阅读了 Npm 文件之后,也许我应该使用 . gyp 文件? 我很困惑。

81803 次浏览

It's not possible to specify dependencies as "global" from a package.json. And, this is by design as Isaac states in that feature request you referenced:

Yeah, we're never going to do this.

But, "binaries" can still be used when a package is installed locally. They'll be in .../node_modules/.bin/. And, you should be able to queue them up with a preinstall script.

Though, if the series of commands is rather lengthy (as "jshint, csslint, buster, etc.." would suggest), you may want to look into using a build tool such as grunt to perform the various tasks:

{
// ...,


"scripts": {
"preinstall": "grunt"
}
}

I really like the pattern where you install local dependencies, then use a bash script that sets your PATH to ./node_modules/.bin.

File: env.sh

# Add your local node_modules bin to the path for this command
export PATH="./node_modules/.bin:$PATH"


# execute the rest of the command
exec "$@"

Then, you can use this script before any bash command. If you pair that with a Makefile or npm script:

File: Makefile

lint :
./env.sh csslint my_styles

File: package.json

"scripts": {
"lint": "./env.sh csslint my_styles"
}

This tasks in these files look like they reference csslint in some global location, but they actually use the version in your node_modules bin.

The really awesome benefit of this is that these dependencies can be versioned easily, just like your other node modules. If you stick with a global install solution, you could be clobbering some specific version on the user's system that is required for one of their other projects.

You should try this: https://github.com/lastboy/package-script

I've been using it to install global npm packages straight from the package.json. It works well for clients who aren't technically literate.

It even checks if the packages are already installed, if not install them!