Search code examples
jsontypescript

How to import package.json in TypeScript?


I'm trying to import my package.json file in TypeScript and it doesn't seem to work. Specifically, I'm just trying to import it so that I can access the name and version properties for a log statement. Something like:

import * as pjson from '../package.json';
// other code here
log.info(`${pjson.name}:${pjson.version}` started on port ...);

We have this same syntax elsewhere in other projects that use Node/Babel, but I'm trying to introduce some TypeScript around these parts. Elsewhere we'd do something like:

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

That doesn't work here however. I followed the instructions at https://www.npmjs.com/package/json-d-ts which at least made the error on my import statement go away, but now when I try to access properties I get the following error:

src/index.ts(20,21): error TS2339: Property 'name' does not exist on type 'typeof import("*.json")'.
src/index.ts(20,35): error TS2339: Property 'version' does not exist on type 'typeof import("*.json")'.

Is there a way to fix this, or do I just have to hardcode these values somewhere (rather than dynamically retrieving them from package.json)? Maybe I can declare a type for import("*.json") somehow with these properties defined on it?


Solution

  • 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.