我正在尝试将 .json 文件导入到角度的打字稿文件中。
import * as languagesData from './../../data/languages.json';
上面的导入语句给出以下错误:
不可触碰的应用程序/库/数据/语言"解析为非模块 实体,并且不能使用此构造导入。
文件夹结构。
library/
projects/
node_modules/
tsconfig.json
typings.d.ts
我已经更新到打字稿版本2.9.2
包.json
"devDependencies": {
"typescript": "^2.9.2"
}
打字.d.ts
declare module "*.json" {
const value: any;
export default value;
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"resolveJsonModule": true,
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"paths": {
"library": [
"library/"
],
"library/*": [
"library/*"
]
}
}
}
library/services/report/report.service.ts
import * as languagesData from './../../data/languages.json';
projects/project-name/src/app/app.component.ts
import { ReportService } from 'library/services/report/report.service';
注意
我有一个"库"文件夹,其中包含可以在我的项目文件夹中包含的多个应用程序之间共享的常见组件和服务。我正在将服务从库中导入到我的应用程序中。服务文件是包含 json 数据的导入语句的文件。
尝试将以下内容添加到您的tsconfig.json中:
"compilerOptions": {
...
"esModuleInterop": true,
...
}
然后以这种方式导入您的 json 文件:
import languagesData from './../../data/languages.json';
这对我有用(角度 6,带有角度 cli(。