Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run "nvm use" automatically in a prestart npm script?

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

package.json file

"scripts": {
  "prestart": "sh test.sh",
  "start": "nodemon index.js"
}

.nvmrc file

4

test.sh file

#!/bin/bash

if [ -d ~/.nvm ]
  then
    source ~/.nvm/nvm.sh

    nvm use
fi

This works and switches 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)

> [email protected] 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 on how to deal with this in a proper way?

Thanks

like image 789
Carl Moravec Avatar asked Dec 15 '15 23:12

Carl Moravec


People also ask

How do I change node version automatically?

node-version at the root of your projects specifying the node version required. After installing avn, when you cd into a directory with a . node-version file, avn will automatically detect the change and use your installed version manager to switch to that version of node.

Does NVM use Nvmrc?

The answer is yes! If you use a modern shell, such as bash or zsh, then there is shell script you can add to your shells configuration file to automatically nvm use and install the node version defined in the . nvmrc file when you change into a directory that has a . nvmrc file in it.

How do I change the default NVM version?

Setting a default NVM version To set the default NVM version, you first have to make sure that version is installed in NVM. We can then run the following command to set this as our default version. You can check which versions you have installed by running the following command.

What should I run before npm install?

You could run $ npm view <package_name> dependencies , (to list the dependencies), before running $ npm install <package_name> as mentioned in the docs. Or must $ npm view <package_name> dependencies be automatically invoked every time you run $ npm view <package_name> ?


1 Answers

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

like image 178
Ribbo Avatar answered Sep 28 '22 08:09

Ribbo