Import the version number from package.json

If you are using Node.js and you have configured package.json as type: "module", you can read the version of it from a file located in the same folder:

import fs from 'fs';

let { version } = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url)));

import.meta.url returns the absolute path to package.json.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.