Is there any way how to run “nvm use” automatically in “prestart” npm script?

最后都变了- 提交于 2019-11-29 08:41:00

问题


I would like to have automatically invoke "nvm use" when I run "npm start". So I come up with this solution:

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:

> 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:

{ 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


回答1:


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.

"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:


Your package.json could look like

"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.

Sorry for the edits cuz I didn't test my first two.



来源:https://stackoverflow.com/questions/34301122/is-there-any-way-how-to-run-nvm-use-automatically-in-prestart-npm-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!