在打字稿中导入 json 文件 Angular 5
Import json file in typescript Angular 5
我正在尝试像那样在打字稿 class 中导入 json 文件
import * as nationalities from './mock/nationalities.json';
它给了我一个错误
Cannot find module './mock/nationalities.json'.
为了解决这个问题,我添加了这个
declare module '*.json' {
const value: any;
export default value;
}
但这并没有解决我的问题,还给我另一个错误异常
Invalid module name in augmentation, module '*.json' cannot be found.
我的 Typescript 版本
2.9.2
基于此 ,这里是 Angular 6+ 的完整答案:
假设您将 json 文件添加到 "json-dir" 目录中:
将"json-dir"添加到angular.json文件中:
"assets": [
"src/assets",
"src/json-dir"
]
允许导入 json 模块以防止 typescript 错误:
Angular 6: 添加到 typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
Angular 7+: 添加到 tsconfig.json
"compilerOptions": {
...
"resolveJsonModule": true
}
从您的控制器、服务或其他任何东西,只需使用此 绝对路径 从 /src
目录导入文件。例如:
import * as myJson from 'absolute/path/to/json/dir/json-file.json';
assuming source files are in src/app
and json files in src/absolute/path/to/json/dir
我正在尝试像那样在打字稿 class 中导入 json 文件
import * as nationalities from './mock/nationalities.json';
它给了我一个错误
Cannot find module './mock/nationalities.json'.
为了解决这个问题,我添加了这个
declare module '*.json' {
const value: any;
export default value;
}
但这并没有解决我的问题,还给我另一个错误异常
Invalid module name in augmentation, module '*.json' cannot be found.
我的 Typescript 版本
2.9.2
基于此
假设您将 json 文件添加到 "json-dir" 目录中:
将"json-dir"添加到angular.json文件中:
"assets": [ "src/assets", "src/json-dir" ]
允许导入 json 模块以防止 typescript 错误:
Angular 6: 添加到
typings.d.ts
declare module "*.json" { const value: any; export default value; }
Angular 7+: 添加到
tsconfig.json
"compilerOptions": { ... "resolveJsonModule": true }
从您的控制器、服务或其他任何东西,只需使用此 绝对路径 从
/src
目录导入文件。例如:import * as myJson from 'absolute/path/to/json/dir/json-file.json';
assuming source files are in
src/app
and json files insrc/absolute/path/to/json/dir