简体   繁体   English

typescript:仅从json文件导入类型

[英]typescript: Import only type from json file

Is there any way to import just JSON file type ? 有什么方法可以只导入JSON文件type I have a complex JSON file and I need it's definition to be used in whole application, but when I do import * as data from 'data.json' , whole file is imported, which causes its presence in build (using webpack). 我有一个复杂的JSON文件,我需要在整个应用程序中使用它的定义,但是当我import * as data from 'data.json' ,整个文件都被导入,这导致它存在于构建中(使用webpack)。 As far as I know, there is no way to exclude it in webpack config . 据我所知,没有办法在webpack config排除它。

EDIT: My question might be a little bit unclear, so here is my example: 编辑:我的问题可能还不清楚,所以这是我的示例:

import * as data from 'data.json'
// data looks like this:
// { 
//   a: {
//    b: 'something1'
//   },
//   c: {
//    d: 'something2'
//   }
// } 

export type typedJson = typeof data;
// which should show on hover/autocomplete: { "a": { "b": "string" }, "c": { "d": "string" } }

But when I do that, whole data.json file is imported and it's present in webpack bundle. 但是,当我这样做时,整个data.json文件将被导入,并存在于webpack捆绑包中。 Is there any way to have those typings and exclude it from bundle? 有什么办法可以将这些类型从包中排除呢?

您可以使用导入类型来获取json文件的类型:

type JsonDataType = typeof import('./data.json')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM