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?
Typescript should be able to do it as follows: import * as pack from "../package. json" // access name and version like this: console. log(pack.name);
You can add dependencies to a package. json file from the command line or by manually editing the package.
The package. json file is normally located at the root directory of a Node. js project. The name field should explain itself: this is the name of your project.
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:
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With