Automatically set required Node version for each site in Trellis?

This is a little esoteric, perhaps, but I’m wondering if there is a smart way to set the required Node version on a per-site basis inside Trellis, so that it is automatically called on a given deploy.

Our Trellis setup includes multiple sites, and, because those sites were all developed at different times — and, as a result, they use different versions of Sage — we have to use NVM to manually switch to the right Node version before each deploy. There may be an obvious technical reason why this isn’t possible, but I’ve wondered if it would be workable to set a variable inside wordpress_sites.yml or build-before.yml, for example, that tells Trellis that requires NVM to switch to Node 12.4.0, and then does that each as part of the deploy process, thereby cutting out the need to remember which site requires which and to select the right one prior to each deploy?

Trellis itself doesn’t really have any concept of what Node version is being used: It just runs the scripts you tell it to. That means you could add a line to build-before.yml that sets the Node version before running the build command:

 - name: Set Node Version
   command: nvm use 16
   deletage_to: localhost
 - name: Install npm dependencies
   command: yarn
   delegate_to: localhost
     chdir: "{{ project_local_path }}/web/app/themes/sage"

(I haven’t tested that, but something like that should probably work.)

1 Like

With nvm you can add a .nvmrc file into the project… just node -v > .nvmrc after you’ve nvm used the right version.

I don’t use Trellis myself, but I imagine then you may be able to have it just call nvm use generally and wherever there is a .nvmrc file it will find the version there.

1 Like

The combination of both of these suggestions should be the ideal solution. If your site requires a specific version of Node, then it should be declared within the codebase (such as in a .nvmrc file) as @EHLOVader said.

Then Trellis’ responsibility is to install nvm, install the needed node versions, and then run nvm use. But Trellis itself shouldn’t know or care what the specific Node version is of a site.

1 Like