gpt4 book ai didi

node.js - Node : how to avoid installing global packages

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:43 26 4
gpt4 key购买 nike

我正在寻找一种模式来避免在使用 Node 时需要全局包,我想使用 npm install 安装我需要的所有东西,然后使用 运行每个命令>npm run xxx,没有安装任何全局包。

例如,我已经配置好运行我的测试。

这些是我的 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
[...]

如果我使用 npm install -g jest 全局安装 jest,一切都运行良好,但这正是我要避免的。

我做出的一些假设可能是错误的:

  • 运行脚本时,node 首先在 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",

但是每次运行npm run test

npx安装jest都需要10多秒

那么,实现它的正确方法是什么?我如何告诉 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。 (查看 this 了解更多信息)

顺便说一句,这个answer对类似的问题可能会有用

关于node.js - Node : how to avoid installing global packages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55097434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com