将Typescript中的json文件作为对象而不是模块加载

问题描述 投票:1回答:1

我正在使用的代码中具有以下导入:

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

现在,schema变量是一个模块,如果要访问JSON对象,则需要执行schema.default。如果将import * as schema更改为import schema,则架构变量为JSON内容(对象)。

我想知道是否可以使用webpack或任何babel插件使用import * as schema加载对象?

当前的babel配置文件:

  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 }]
  ]
typescript webpack babel
1个回答
0
投票

我已经在/ src /文件夹中使用以下代码创建了typings.d.ts

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

在我的组件中:

import data from "./data.json"

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

重新运行服务器并正常工作

© www.soinside.com 2019 - 2024. All rights reserved.