I’m trying to import a JSON file into a .tsx file in TypeScript but encounter an error. Here’s what I have:
JSON file (colors.json):
{
"primaryBright": "#2DC6FB",
"primaryMain": "#05B4F0",
"primaryDarker": "#04A1D7",
"primaryDarkest": "#048FBE",
"secondaryBright": "#4CD2C0",
"secondaryMain": "#00BFA5",
"secondaryDarker": "#009884",
"secondaryDarkest": "#007F6E",
"tertiaryMain": "#FA555A",
"tertiaryDarker": "#F93C42",
"tertiaryDarkest": "#F9232A",
"darkGrey": "#333333",
"lightGrey": "#777777"
}
TypeScript setup:
In the type definition file:
declare module "*.json" {
const value: any;
export default value;
}
Importing in .tsx file:
import colors = require('../colors.json');
Using it:
const color = colors.primaryMain;
Error:
Property ‘primaryMain’ does not exist on type ‘typeof “*.json”’
How can I fix this issue with TypeScript to correctly read the JSON file?
To fix the issue with TypeScript reading the JSON file, you can use the TypeScript 2.9+ feature:
Enable the --resolveJsonModule
compiler flag in your tsconfig.json
to allow TypeScript to handle JSON imports natively:
{
"compilerOptions": {
"resolveJsonModule": true
}
}
Then, import the JSON directly:
import colors from '../colors.json';
console.log(colors.primaryMain);
This method leverages a built-in TypeScript feature that allows JSON files to be imported directly as modules. It simplifies the process by removing the need for custom module declarations.
Setup:
Enable the resolveJsonModule
compiler option in your tsconfig.json
.
Usage:
import colors from '../colors.json';
Alternatively, if you prefer not to enable resolveJsonModule
, you can use a custom module declaration. Adjust your import to match the module declaration:
Custom Module Declaration:
declare module "*.json" {
const value: any;
export default value;
}
Import Statement:
import * as colors from '../colors.json';
console.log(colors.default.primaryMain);
This method involves creating a custom module declaration to handle JSON imports. It specifies that JSON files export a default value.
Setup:
Define a module declaration in a .d.ts
file.
Usage:
You need to import using import * as colors from '../colors.json';
or other compatible import forms.
Ensure you are not mixing import styles. For import = require()
, you should access the default export:
Correct Import Syntax:
import colors = require('../colors.json');
console.log(colors.default.primaryMain);
This approach uses CommonJS-style require
for importing JSON, which is compatible with the module declaration that exports JSON as default.
Setup:
No additional configuration is needed if using require
, but ensure that the import statement matches the module declaration.
Usage:
import colors = require('../colors.json');
By following these methods, you can correctly handle JSON file imports in TypeScript, ensuring TypeScript can read the JSON file without errors.