Sunday, 10 January 2021

Use json Data in a typescript project

Let's say that you have some json data that you would like to leverage in your project, could be something like config files. well you can import the module like so

    import('@/mockData/fingerRational.json')
      .then(module => this.fingerRational = (module.default as unknownas IFingerRational[]);

However you will get an error saying something like

Module '@/mockData/fingerRational.json' was resolved to 'd:/dev/eDoc_Panels_Frontend/trunk/src/mockData/fingerRational.json', but '--resolveJsonModule' is not used.ts(7042)

the solution is simple you have to modify your tsconfig.json file

{
  "compilerOptions": {
    "target""esnext",
    "module""esnext",
    "strict"true,
    "jsx""preserve",
    "importHelpers"true,
    "resolveJsonModule"true//<----- added for mock data
    "moduleResolution""node",
    "experimentalDecorators"true,
    "skipLibCheck"true,
    "esModuleInterop"true,
    "allowSyntheticDefaultImports"true,
    "sourceMap"true,
    "baseUrl"".",
    "types": [
      "webpack-env",
      "jest",
      "webpack",
      "w3c-image-capture"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

and voilia all should be well