I would like to have automatically invoke "nvm use" when I run "npm start". So I come up with this solution:
我想在运行“npm start”时自动调用“nvm use”。所以我想出了这个解决方案:
package.json
"scripts": {
"prestart": "sh test.sh",
"start": "nodemon index.js"
}
.nvmrc
4
test.sh
#!/bin/bash
if [ -d ~/.nvm ]
then
source ~/.nvm/nvm.sh
nvm use
fi
This works and switch between nvm versions console output is:
这工作和nvm版本之间切换控制台输出是:
> sh test.sh
Found '/my-user-path/.nvmrc' with version <4>
Now using node v4.2.2 (npm v2.14.7)
> app@1.0.0 start /app-path/
> nodemon index.js
But when I call form index.js "console.log(process.versions);" nvm script is executed probably in different process so output is:
但是当我调用form index.js“console.log(process.versions);”时nvm脚本可能在不同的进程中执行,因此输出为:
{ http_parser: '2.6.0',
node: '5.1.0',
v8: '4.6.85.31',
uv: '1.7.5',
zlib: '1.2.8',
ares: '1.10.1-DEV',
icu: '56.1',
modules: '47',
openssl: '1.0.2d' }
Any suggestions how to deal with this in proper way?
有任何建议如何正确处理这个问题?
Thanks
2 个解决方案
#1
5
Generally on a Mac, the nvm.sh file is located in your home path. Use the $HOME variable if you have multiple Mac users working on the code.
通常在Mac上,nvm.sh文件位于主路径中。如果有多个Mac用户在使用代码,请使用$ HOME变量。
"scripts": {
"prestart": "source $HOME/.nvm/nvm.sh; nvm use"
}
I would've added this as a comment to the above response, but I'm not allowed :(
我会将此作为对上述回复的评论添加,但我不允许:(
#2
1
Your package.json could look like
你的package.json看起来像
"scripts": {
"start": "source /whereever/located/nvm.sh; nvm use; nodemon index.js"
}
To explain. The "start" line is a single shell instance. So you have to have nvm initialize the PATH in that shell instance. Also, nvm
is a shell function not an executable shell script. The nvm function lives in the shell instance, and is created by sourcing the nvm.sh file.
解释。 “start”行是一个shell实例。所以你必须让nvm初始化那个shell实例中的PATH。此外,nvm是一个shell函数,而不是一个可执行的shell脚本。 nvm函数存在于shell实例中,并通过获取nvm.sh文件来创建。
Sorry for the edits cuz I didn't test my first two.
抱歉编辑因为我没有测试我的前两个。
#1
5
Generally on a Mac, the nvm.sh file is located in your home path. Use the $HOME variable if you have multiple Mac users working on the code.
通常在Mac上,nvm.sh文件位于主路径中。如果有多个Mac用户在使用代码,请使用$ HOME变量。
"scripts": {
"prestart": "source $HOME/.nvm/nvm.sh; nvm use"
}
I would've added this as a comment to the above response, but I'm not allowed :(
我会将此作为对上述回复的评论添加,但我不允许:(
#2
1
Your package.json could look like
你的package.json看起来像
"scripts": {
"start": "source /whereever/located/nvm.sh; nvm use; nodemon index.js"
}
To explain. The "start" line is a single shell instance. So you have to have nvm initialize the PATH in that shell instance. Also, nvm
is a shell function not an executable shell script. The nvm function lives in the shell instance, and is created by sourcing the nvm.sh file.
解释。 “start”行是一个shell实例。所以你必须让nvm初始化那个shell实例中的PATH。此外,nvm是一个shell函数,而不是一个可执行的shell脚本。 nvm函数存在于shell实例中,并通过获取nvm.sh文件来创建。
Sorry for the edits cuz I didn't test my first two.
抱歉编辑因为我没有测试我的前两个。