node.js - 节点:如何避免安装全局包
问题描述
我正在寻找一种模式来避免在使用节点时需要全局包,我想安装我需要的所有东西npm install
,然后只使用 运行每个命令npm run xxx
,而不安装任何全局包。
例如,我已将 jest 配置为运行我的测试。
这些是我的 package.json 中的依赖项:
[...]
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/express": "^4.16.1",
"@types/node": "^11.10.5",
"express": "^4.16.4",
"ts-node-dev": "^1.0.0-pre.32",
"typescript": "^3.3.3333"
},
"devDependencies": {
"@types/jest": "^24.0.9",
"@types/supertest": "^2.0.7",
"jest": "^24.3.1",
"nodemon": "^1.18.10",
"supertest": "^4.0.0",
"ts-jest": "^24.0.0"
}
[...]
这些是我配置的一些脚本:
[...]
"scripts": {
"test": "jest --coverage",
"tsc": "tsc",
"watch": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/server.ts"
},
[...]
但是当我发出npm run test
这个错误时:
$ npm run test
> ci-test@0.0.1 test /home/sas/devel/apps/vue/ci-test
> jest --coverage
sh: 1: jest: not found
npm ERR! file sh
[...]
如果我在全球范围内安装 jest 并且npm install -g jest
一切运行良好,但这正是我想要避免的。
我做出的一些假设可能是错误的:
运行脚本时,节点首先在 node_modules/.bin 中查找命令(以便使用本地安装的包)
当我发出
npm install
每个命令行命令时,都会安装到 node_modules/.bin
最后一个不起作用,因为即使我的 devDependencies 中有 jest,我的项目中也没有 node_modules/.bin/jest 文件
$ ls node_modules/.bin/
acorn cdl esgenerate esvalidate is-ci json5 loose-envify mime nodetouch parser semver sshpk-sign strip-indent watch
atob escodegen esparse import-local-fixture jsesc js-yaml marked mkdirp nopt rc sshpk-conv sshpk-verify uglifyjs
另一方面,作为一种解决方法,以下似乎可行:
"scripts": {
"test": "npx jest --coverage",
但是每次我运行 npx 安装 jest 需要超过 10 秒npm run test
那么,实现它的正确方法是什么?O 如何告诉 npm 将 jest 安装到 node_modules/.bin 并在我的脚本中引用它时使用它?
解决方案
似乎比预期的要容易,我只需要发出:
npm install --only=dev
似乎默认情况下 npm 不会安装开发依赖项
我做了几个测试,使用 NODE_ENV var,在取消设置后npm install
似乎还安装了 devDependencies,以及 node_modules/.bin/jest 中的 jest。似乎以某种方式假设我处于生产模式。
我学会的另一个避免安装全局依赖项的技巧是使用 --save-dev 安装它,然后添加一个脚本来运行它npm run
。例如,为了避免全局安装 jest 但仍然能够从命令行使用它,您应该:
npm install jest --save-dev
然后将以下内容添加到您的 package.json
scripts: {
"jest": "jest"
}
然后你可以从命令行使用npm run jest
. 要从命令行传递参数,您必须在参数之前添加一个“--”,如下所示npm run jest -- --coverage
:或者你可以发出npx jest --coverage
,如果安装了,npx 将使用 node_modules/.bin 中的 jest。(检查此以获取更多信息)
顺便说一句,这个类似问题的答案可能很有用
推荐阅读
- javascript - 单个数组时间戳作为多个系列的 xAxis
- javascript - 如何使用回退方法在 Xamarin Forms iOS 中实现深度链接
- java - 获取当前正在播放的 Windows 媒体控制栏的歌曲?(爪哇)
- xml - 我们如何使用作为 cron 运行的 Jenkins 作业作为监控仪表板
- c# - XML序列化同一对象的不同elementName
- node.js - Node.js 客户端库对 Gmail API 的批量请求
- docker - 使用旧数据恢复结构网络时出现权限被拒绝错误
- flutter - Draggscroll图像颤动,可能吗?
- node.js - Lambda 节点“hello undefined”异步/等待不起作用?
- python - win32com python 异常行为