在Typescript Angular 5中导入json文件 [英] Import json file in typescript Angular 5
问题描述
我正在尝试像这样的typescript类中导入json文件
I am trying to import json file in typescript class like that
import * as nationalities from './mock/nationalities.json';
这给我一个错误
找不到模块'./mock/nationalities.json'.
Cannot find module './mock/nationalities.json'.
为解决此问题,我添加了此
and to solve this issue I added this
declare module '*.json' {
const value: any;
export default value;
}
但是它不能解决我的问题,并且还会给我另一个错误异常
but it doesn't solve my issue and also gives my another error exception
扩充中的模块名称无效,找不到模块'* .json'.
Invalid module name in augmentation, module '*.json' cannot be found.
我的打字稿版本
2.9.2
2.9.2
推荐答案
Based on this post, here is complete answer for Angular 6+:
假设您将json文件添加到"json-dir"目录中:
Suppose you added your json files into "json-dir" directory:
-
将"json-dir"添加到angular.json文件中:
add "json-dir" into angular.json file :
"assets": [
"src/assets",
"src/json-dir"
]
允许导入json模块以防止打字稿错误:
allow import of json modules to prevent from typescript errors:
角度6:添加到typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
Angular 7+:添加到tsconfig.json
Angular 7+: add to tsconfig.json
"compilerOptions": {
...
"resolveJsonModule": true
}
从您的控制器,服务或其他任何东西,只需使用/src
目录中的此绝对路径导入文件.例如:
from your controller, service or anything else, simply import the file by using this absolute path from /src
directory. For example:
import * as myJson from 'absolute/path/to/json/dir/json-file.json';
假设源文件在
src/app
中,而json文件在src/absolute/path/to/json/dir
assuming source files are in
src/app
and json files insrc/absolute/path/to/json/dir
这篇关于在Typescript Angular 5中导入json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!