Load json file in Typescript as an object instead of a module

Viewed 551

I have the following import in a code I am using:

import * as schema from "../schema.json";

Right now, the schema variable is a module and if I want to access my JSON object, I need to do schema.default. If I change import * as schema to import schema, then the schema variable is the JSON content (an object).

I was wondering if it was possible using webpack or any babel plugin to load an object with import * as schema ?

Current babel config file:

  presets: ['@babel/preset-typescript', '@babel/preset-react', ['@babel/preset-env', { modules: 'commonjs' }]],
  plugins: [
    'babel-plugin-dynamic-import-node',
    '@babel/plugin-transform-destructuring',
    ['@babel/plugin-transform-for-of', { loose: true }],
    '@babel/plugin-transform-regenerator',
    '@babel/plugin-transform-runtime',
      // ["@babel/plugin-transform-typescript", {allowNamespaces: true}],
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    '@babel/plugin-proposal-object-rest-spread',
    ['styled-components', { ssr: true }]
  ]
1 Answers

I have created a typings.d.ts in /src/ folder with following code:

}
declare module "*.json" {
  const value: any
  export default value
}

And in my component:

import data from "./data.json"

export default function MyComponent() {
  return (
    <div>
      {data.map(elem => (
        <h1> {elem.title}</h1> 
        <p> {elem.body}</p>
      )}
     </div>
)}

Re-run the server and it worked

Related