JSON imports in TypeScript

by Benny Neugebauer

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

// Pros:
// https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
// JSON fields are automatically typed

// Cons:
// Requires TypeScript 2.9+
// Needs "moduleResolution": "node" in "tsconfig.json"
// Needs "resolveJsonModule": true in "tsconfig.json"
// JSON files need to be inside of the "rootDir" (tsconfig.json)

// Typical errors:
// error TS5070: Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.
// error TS6059: File 'package.json' is not under 'rootDir'. 'rootDir' is expected to contain all source files.

const {version}: {version: string} = require('../package.json');

// Pros:
// No need to adjust "tsconfig.json"

// Cons:
// No automatically typing