I discovered something neat that is possible in TypeScript. Did you know that you can import JSON as a Javascript module? I didn't...
I had a configuration file like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"server": { | |
"url": "http://localhost" | |
} | |
} |
In my tsconfig.json I had to set the resolveJsonModule
to true:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
{ | |
"compilerOptions": { | |
"module": "commonjs", | |
"noImplicitAny": true, | |
"removeComments": true, | |
"preserveConstEnums": true, | |
"sourceMap": true, | |
"resolveJsonModule": true, | |
"esModuleInterop":true | |
} | |
} |
Now I could import the config file as a module. The nice thing is that I even get type checking and autocompletion!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import config from './config.json'; | |
console.log(config); |
Remark: Not enabling this option out of the box was done by the TypeScript team to avoid pulling in large JSON files that would consume a lot of memory.