N Kaushik

How to find the package.json version in JavaScript/TypeScript npm project

August 24, 2021

How to find the package.json version in a npm project:

For a npm project, there is a version property in it. A basic package.json looks as like below:

{
  "name": "typescript-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "tsc": "tsc hello.ts -w",
    "nodemon": "nodemon hello.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.12",
    "typescript": "^4.3.2"
  }
}

version is important if you want to publish your package. You can also use this to keep tracking what is the current version your project is using.

There are two easy way to read this version. In this post, I will show you how to do that.

Importance of version of package.json:

name and version fields are optional fields if you don’t want to publish your package. But, if you are publishing the package, it should include name and version.

The combination of name and version should be unique always. If you are publishing a new version for your package, you need to change the version for each release.

Method 1: Read version from the environment variable:

process.env or environment variable holds the version info. You can read it as like below:

const v = process.env.npm_package_version;

Method 2: Read the version directly from package.json:

You can also read it directly from the package.json file. For example:

import {version} from './package.json';

It reads the data from the .json file.

You can choose any of these methods. npm_package_version is available only if you are starting it as a npm project using any npm command like npm start.

Method 3: Using another library:

You can also use genversion, it is a popular open sourced library to read the version. This is the Github page link.


Subscribe to my Newsletter