How to import package.json in TypeScript?

npm exports package.json attributes as env vars with the the prefix npm_package_ as described in npm docs
So if you're using npm you can get the version as process.env.npm_package_version


How to import *.json ?

As already answered you need Typescript >= 2.9 and the following settings in tsconfig.json:

{
  "resolveJsonModule": true,
  "esModuleInterop": true,
  "module": "commonjs"
}

But there are restrictions:

  • You must compile to CommonJS
  • All your imported JSONs must reside under the "rootDir"

Unfortunately the "rootDir" is very often a folder beneath package.json like './src' and things would fail.

So:
How to import package.json ? You can require it:
const pjson = require('../package.json');

If you use npm.start: you don't need to :

The package.json fields are tacked onto the npm_package_ prefix. So, for instance, if you had {"name":"foo", "version":"1.2.5"} in your package.json file, then your package scripts would have the npm_package_name environment variable set to “foo”, and the npm_package_version set to “1.2.5”. You can access these variables in your code with process.env.npm_package_name and process.env.npm_package_version, and so on for other fields.