DEV Community

Narendra Sisodiya ⚛️ 🇮🇳
Narendra Sisodiya ⚛️ 🇮🇳

Posted on

How to fix node version in a Web-App

How we can fix not version so that developer, CI/CD, production, everybody uses the same node version?

Step 1 — Add nodeVersionLock in package.json

We need to add preinstall and prestart scripts too.
package.json will look like this

{
  "name": "metaindex-frontend",
  "nodeVersionLock": "14.13.0",
  "scripts": {
    "preinstall": "node ./system/npm/preinstall.js",
    "prestart": "node ./system/npm/preinstall.js",
    "start": "run-p build:tailwindcss start:watchtailwindcss start:cra",
    "start:cra": "react-scripts start",
   }
}

Step 2 — Throw errors when undesired node-version found.

Content of ./system/npm/preinstall.js

const pkgJson = require('../../package.json');

const nodeVersion = process.versions.node;
let err = false;

if (pkgJson.nodeVersionLock !== nodeVersion) {
  console.error(`Please use node ${pkgJson.nodeVersionLock}. Try
    nvm install v${pkgJson.nodeVersionLock}
    nvm reinstall-packages v${nodeVersion}
    nvm uninstall v${nodeVersion}
  `);
  err = true;
} else {
  console.error(`Thanks for using Latest Node version ${pkgJson.nodeVersionLock}.\n`);
}

if (err) {
  console.error('');
  process.exit(1);
}

Step 3— AutoUpdate of Dockerfile & GitbHub YML

This step is optional and custom. it depends on your setup.

Content of ./system/npm/fix-node-versions.js

const fs = require('fs');
const YAML = require('yamljs');
const replaceFirstLineOfFile = require('file-firstline-replace');
const pkgJson = require('../../package.json');

var filename = 'Dockerfile';
var newHeader = `FROM node:${pkgJson.nodeVersionLock} as builder\n`;
replaceFirstLineOfFile(filename, newHeader, function (error) {
  if (error) {
    throw error;
  }
  console.warn('Dockerfile updated');
});

// Replace in gitlab ci file.

var gitlabCiYml = fs.readFileSync('.github/workflows/node.js.yml', 'utf8');

// parse YAML string
var gitlabCiJSON = YAML.parse(gitlabCiYml);
gitlabCiJSON.jobs.build.strategy.matrix['node-version'][0] = pkgJson.nodeVersionLock;
var spaces = 4;
var gitlabCiYmlUpdated = YAML.stringify(gitlabCiJSON, spaces);

fs.writeFileSync('.github/workflows/node.js.yml', gitlabCiYmlUpdated, 'utf8');
console.warn('github CI file updated');

Top comments (0)