{"id":374,"date":"2020-09-04T12:01:13","date_gmt":"2020-09-04T10:01:13","guid":{"rendered":"http:\/\/www.myblog.nguenkam.com\/?p=374"},"modified":"2021-11-30T12:31:43","modified_gmt":"2021-11-30T11:31:43","slug":"importing-json-modules-in-typescript","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2020\/09\/04\/importing-json-modules-in-typescript\/","title":{"rendered":"Importing JSON Modules \/Files in TypeScript"},"content":{"rendered":"\n<p>TypeScript 2.9 introduced a new&nbsp;<code>--resolveJsonModule<\/code>&nbsp;compiler option that lets us import JSON modules from within TypeScript modules.<\/p>\n\n\n\n<h4>#Importing JSON Modules via&nbsp;<code>require<\/code>&nbsp;Calls<\/h4>\n\n\n\n<p>Let&#8217;s assume we have a Node application written in TypeScript, and let&#8217;s say that we want to import the following JSON file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"server\": {\n    \"nodePort\": 8080\n  }\n}<\/code><\/pre>\n\n\n\n<p>In Node, we can use a&nbsp;<code>require<\/code>&nbsp;call to import this JSON file like any other CommonJS module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const config = require(\".\/config.json\");\n<\/code><\/pre>\n\n\n\n<p>The JSON is automatically deserialized into a plain JavaScript object. This allows us to easily access the properties of our config object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\"use strict\";\n\nconst express = require(\"express\");\nconst config = require(\".\/config.json\");\n\nconst app = express();\n\napp.listen(config.server.nodePort, () =&gt; {\n  console.log(`Listening on port ${config.server.nodePort} ...`);\n});\n<\/code><\/pre>\n\n\n\n<p>So far, so good!<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4># Importing JSON Files via Static&nbsp;<code>import<\/code>&nbsp;Declarations<\/h4>\n\n\n\n<p>Let&#8217;s now say we want to use native ECMAScript modules instead of CommonJS modules. This means we&#8217;ll have to convert our&nbsp;<code>require<\/code>&nbsp;calls to static&nbsp;<code>import<\/code>&nbsp;declarations:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ We no longer need the \"use strict\" directive since\n\/\/ all ECMAScript modules implicitly use strict mode.\n\nimport * as express from \"express\";\nimport * as config from \".\/config.json\";\n\nconst app = express();\n\napp.listen(config.server.nodePort, () =&gt; {\n  console.log(`Listening on port ${config.server.nodePort} ...`);\n});<\/code><\/pre>\n\n\n\n<p class=\"has-vivid-red-color has-text-color\"><strong><em>Now, we get a type error in line 2. TypeScript doesn&#8217;t let us import a JSON module out of the box, just like that.<\/em><\/strong><\/p>\n\n\n\n<p>Let&#8217;s head over to our&nbsp;<em>tsconfig.json<\/em>&nbsp;file and enable the&nbsp;<code>resolveJsonModule<\/code>&nbsp;option there:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"compilerOptions\": {\n    \"target\": \"es2015\",\n    \"module\": \"commonjs\",\n    \"strict\": true,\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true\n  }\n}\n<\/code><\/pre>\n\n\n\n<p>With&nbsp;<code>--resolveJsonModule<\/code>&nbsp;enabled, we no longer get a type error in our TypeScript file. Even better, we now get type checking and autocompletion!<\/p>\n\n\n\n<p><span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong><em>And there you go! This is how to import JSON modules from within TypeScript modules, only one compiler option away.<\/em><\/strong><\/span><\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h3>Definition type File.<\/h3>\n\n\n\n<p>Since TypeScript 2.9, we can use the&nbsp;<a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/release-notes\/typescript-2-9.html\"><code>--resolveJsonModule<\/code>&nbsp;compiler flag<\/a>&nbsp;to have TypeScript analyze imported&nbsp;<code>.json<\/code>&nbsp;files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. <\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>However, sometimes, for different reasons it might be,  we still need to define the format of our Objet.  And for that, we can do it in 2 differents ways :<\/p><\/blockquote>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">1 -Use of &#8220;esModuleInterop&#8221; compiler fla<\/span><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>{\r\n  \"compilerOptions\": {\r\n    \"target\": \"es2015\",\r\n    \"module\": \"commonjs\",\r\n    \"strict\": true,\r\n    \"moduleResolution\": \"node\",\r\n    \"resolveJsonModule\": true,\n    <span class=\"has-inline-color has-vivid-cyan-blue-color\">\"esModuleInterop\"<\/span>: <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>true<\/strong><\/span>,\r\n  }\r\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"259\" height=\"331\" src=\"https:\/\/www.myblog.nguenkam.com\/wp-content\/uploads\/2020\/09\/esModuleInterOp.png\" alt=\"\" class=\"wp-image-392\" srcset=\"https:\/\/nguenkam.com\/blog\/wp-content\/uploads\/2020\/09\/esModuleInterOp.png 259w, https:\/\/nguenkam.com\/blog\/wp-content\/uploads\/2020\/09\/esModuleInterOp-235x300.png 235w\" sizes=\"(max-width: 259px) 100vw, 259px\" \/><\/figure>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">2 &#8211; Adding extra @Type definitions (typing.d.ts), as followed:<\/span><\/h4>\n\n\n\n<p>let\u00b4s create a typing.d.ts file, and define the declarations module, for all JSON files. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>declare module \"*.json\" {\n  const value: any;\n  export default value;\n}<\/code><\/pre>\n\n\n\n<p>That way, we  are stating that all modules that have a specifier ending in&nbsp;<code>.json<\/code>&nbsp;have a single export&nbsp;<em>named<\/em>&nbsp;<code>default<\/code>.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4><em>How to use our Object JSON in the application ? <\/em><\/h4>\n\n\n\n<h4>Example: <\/h4>\n\n\n\n<p>Let\u00b4s say we have a&nbsp;<code>JSON<\/code>&nbsp;file that looks like following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n \"primaryBright\":    \"#2DC6FB\",\n  \"primaryMain\":      \"#05B4F0\",\n  \"darkGrey\":         \"#333333\",\n  \"lightGrey\":        \"#777777\"\n}<\/code><\/pre>\n\n\n\n<p>There are several ways you can correctly consume such a module including<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import a from \"a.json\";\n\n\/\/then in the code, you can use it that way:\na.primaryMain<\/code><\/pre>\n\n\n\n<p>and<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import * as a from \"a.json\";\n\n\/\/then in the code, you can use it that way:\na.default.primaryMain<\/code><\/pre>\n\n\n\n<p>and<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import {default as a} from \"a.json\";\n\n\/\/then in the code, you can use it that way:\na.primaryMain<\/code><\/pre>\n\n\n\n<p>and<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import a = require(\"a.json\");\n\n\/\/then in the code, you can use it that way:\na.default.primaryMain<\/code><\/pre>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p><\/p>\n\n\n\n<h4># Using Dynamic Imports:<\/h4>\n\n\n\n<p>Some time, we might need to import the file dynamically.  <\/p>\n\n\n\n<p>For e.g. based on some condition, import file 1<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if (condition){\r\n    \/\/ import file1;\r\n }<\/code><\/pre>\n\n\n\n<p>And that\u00b4s  how, we will make the import: ( see code below)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const data_json = import(\"..\/app_data_files\/file1.json\");<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Note: Dynamic Import will return a promise. you can either use async\/await or .then to get the json objects<\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>TypeScript 2.9 introduced a new&nbsp;&#8211;resolveJsonModule&nbsp;compiler option that lets us import JSON modules from within TypeScript modules. #Importing JSON Modules via&nbsp;require&nbsp;Calls Let&#8217;s assume we have a Node application written in TypeScript, and let&#8217;s say that we want to import the following JSON file: In Node, we can use a&nbsp;require&nbsp;call to import this JSON file like any [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1,83],"tags":[81,97,87],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/374"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=374"}],"version-history":[{"count":12,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/374\/revisions"}],"predecessor-version":[{"id":1452,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/374\/revisions\/1452"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=374"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=374"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=374"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}