Join my Laravel for REST API's course on Udemy 👀

Resolve JSON files as modules in TypeScript

May 2, 2022  ‐ 1 min read

Using JSON files and its contents is a useful practice in Node.js projects.

TypeScript version 2.9 (which released in 2018) allows for JSON file imports with the introduction of the resolveJsonModule compiler option, this provides type-safety and allows for handy autocompletion using intellisense in your editor.

If you would try to import a JSON file you can expect an error message like: "Cannot find module './package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension."

As the error message suggest the option you want to use is resolveJsonModule. You can set this compiler option to true in the tsconfig.json file.

{
  "include": ["src/**/*.json"],
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

Optionally you need to adjust the "include" property of your JSON as well, as shown in the example above.

With that being done, you should be able to import a JSON file as a JavaScript module.

import package from "./package.json";