Borislav Hadzhiev
Fri Mar 04 2022·2 min read
Photo by Dhruv
To import a JSON file in TypeScript:
resolveJsonModule
to true
in your tsconfig.json
file.esModuleInterop
to true
in tsconfig.json
.import employee from './employee.json'
.The first thing you should do is make sure you have set resolveJsonModule
and
esModuleInterop
to true
in your tsconfig.json
file.
{ "compilerOptions": { // ... other options "esModuleInterop": true, "resolveJsonModule": true } }
Here is the JSON file we will import in a TypeScript file.
{ "id": 1, "name": "James Doe", "salary": 100, "years": [2022, 2023, 2024] }
And here is how we import the JSON file in an index.ts
file.
import employee from './employee.json'; // 👇️ "JAMES DOE" console.log(employee.name.toUpperCase()); // 👇️ [2022, 2023, 2024] console.log(employee.years);
Make sure to correct the path to the employee.json
file if you have to.
The example above assumes that the employee.json
file and index.ts
are
located in the same directory. If, for example, your employee.json
file was
one directory up, you would import it as
import employee from '../employee.json'
.
If you get an error, try setting moduleResolution
to node
in your
tsconfig.json
file.
{ "compilerOptions": { // ... other settings "moduleResolution": "node", "esModuleInterop": true, "resolveJsonModule": true } }
You should also make sure that the json
file you are importing is located
under your rootDir
.
rootDir
setting in my tsconfig.json
is set to src
, which means that the json
file I am importing has to be located under the src
directory.If your json
file is not under your rootDir
, you would get an error: "File
is not under 'rootDir'. 'rootDir' is expected to contain all source files.".
If the you are still unable to import the json file, try importing it as:
import * as employee from './employee.json'; // 👇️ "James Doe" console.log(employee.name.toUpperCase()); // 👇️ [2022, 2023, 2024] console.log(employee.years);
The esModuleInterop
option is set to false
by default, which causes it to treat CommonJS modules
similar to ES6 modules. This causes some issues.
Setting esModuleInterop
to true
fixes these issues.
The
resolveJSONModule
option allows us to import modules with .json
extension in our TypeScript
files.
The resolveJSONModule
option is set to false
by default, so make sure to set
it to true
in your tsconfig.json
file.
If the option is set to false
, you would get an error - "Cannot find module
'./employee.json'. Consider using '--resolveJsonModule' to import module with
'.json' extension.ts(2732)".
import
based on the static JSON shape and enables autocomplete in your IDE.The rootDir option points to the longest common path of all non-declaration input files.
The setting enforces that all files which need to be emitted are under the
rootDir
path. Which means that your .json
file has to be under the specified
rootDir
for the import to work.