How to import package.json in TypeScript? How to import package.json in TypeScript? typescript typescript

How to import package.json in TypeScript?


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.


Since TypeScript 2.9 you can import JSON files as described here:typescriptlang documentation 2.9#json, for this you need to enable the "resolveJsonModule" option in your tsconfig.json.

You need typescript version 2.9 in your project:

npm i typescript@latest --save or yarn add typescript

if you are building the typescript files from the command line with tsc, you will need to install the latest typescript version globally:

npm i -g typescript@latest or yarn global add typescript

if you are building your project with webpack and webpack-dev-server you need to make sure that json files are hosted in the webpack-dev-server context as static files. And even if you hosted them, you can't import json files in the web environment like this, you would need to load the json file with an ajax request and parse the response with JSON.parse.


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