且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用package.json在全局和本地安装依赖项

更新时间:2022-06-11 22:42:34

新注释:您可能不需要或不需要这样做.您可能想要做的只是将那些用于构建/测试等类型的命令依赖项放在package.json的devDependencies部分中. 每当您在package.json中使用scripts中的内容时,devDependencies命令(在node_modules/.bin中)的行为就好像它们在您的路径中一样.

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

例如:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

然后在package.json中

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

然后在命令提示符下运行:

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

但是如果您真的要全局安装,则可以在package.json的脚本部分中添加预安装:

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

所以实际上我的npm安装会再次执行npm安装..这很奇怪,但似乎可行.

So actually my npm install executes npm install again .. which is weird but seems to work.

注意:如果您使用的是npm的最常见设置(其中需要全局Node软件包安装sudo),则可能会出现问题.一种选择是更改您的npm配置,因此不必要:

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm,通过将export PATH=$HOME/npm/bin:$PATH附加到~/.bashrc,将$ HOME/npm/bin添加到$ PATH.

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.