Home > Blockchain >  Using nvm in a makefile to switch node environment
Using nvm in a makefile to switch node environment

Time:04-26

I am trying to use Makefile to build Node projects. As a first step, I want to set node version using NVM. I tried the following code for that:

.PHONY: viz-ui
viz-ui:
    . ${HOME}/.nvm/nvm.sh && nvm use 14.17.0
    node -v

I set nvm use 16 before running make to test the output. After running make viz-ui, I get the following output:

. /home/vijayth2/.nvm/nvm.sh && nvm use 14.17.0
Now using node v14.17.0 (npm v6.14.13)
node -v
v16.14.2

In short, the node switch to 14.17.0 is not reflecting in the makefile, how can i fix it? Or what is the gap in my understanding of this?

CodePudding user response:

Every line of a recipe is run in a brand-new shell. Therefore, when you reach node -v line, it is executed in a new shell that knows nothing about previous one that has set up different node version (this was executed in a separate shell and long gone).

You have basically two options:

  1. Rewrite the recipe so that it all runs in a single shell invocation, e.g.:
.PHONY: viz-ui
viz-ui:
    . ${HOME}/.nvm/nvm.sh && nvm use 14.17.0; \
    node -v

or

  1. Make use of .ONESHELL directive, so that all the recipe is executed in a single shell.
  • Related