Dynamically retrieving the version of a Node.JS/Typescript dependency, at runtime

Something I've needed for a side project is the ability to retrieve what version of a dependency has currently been resolved. It was quite hard to search around this online so I'm writing how to do it for future folks searching for this.

The below examples are based on this example project on GitLab.com.

Let's say that we loosely pin typescript, but at runtime want to log out what version the following resolves to:

{
  "devDependencies": {
    "typescript": "^4.x"
  }
}

Fortunately all NPM packages get distributed with their package.jsons intact, so we can require/import the file and then log it out.

Node.JS

With Node.JS this is trivial, as we can simply require the file, and then interact with it as an object:

const packageJson = require('typescript/package.json');

console.log(`Currently running TypeScript v${packageJson.version}`);

When we run it:

node index.js
# Outputs:
# Currently running Typescript v4.9.5

TypeScript

TypeScript requires a slightly more complex setup, as we need to specify the resolveJsonModule compiler option, which means we have a tsconfig.json similar to:

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

Then, we can write the following code:

import * as packageJson from 'typescript/package.json';

console.log(`Currently running Typescript v${packageJson.version}`);

Therefore, we can run:

npm run build
node dist/index.js
# Outputs:
# Currently running Typescript v4.9.5

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #nodejs #typescript.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.