无法从我的角度库组件导入json

San*_*mas 8 angular-cli angular angular-cli-v6

如果你想帮我检查一下发生了什么,这里是Github的存储库:https://github.com/sandrocsimas/ngx-material-palette-picker

我正在尝试创建我的第一个角度库.我使用angular cli命令生成代码:

ng new ngx-material-palette-picker-app
ng generate library ngx-material-palette-picker
Run Code Online (Sandbox Code Playgroud)

NgxMaterialPalettePickerComponent我正在导入json文件的组件中,但构建引发了以下错误:

projects/ngx-material-palette-picker/src/lib/ngx-material-palette-picker.component.ts(2,31): error TS2307: Cannot find module './palettes.json'.
Run Code Online (Sandbox Code Playgroud)

这是我的组成部分:

import {Component, OnInit} from '@angular/core';
import * as palettesJSON from './palettes.json';

@Component({
  selector: 'ngx-mpp',
  template: `,
  styles: []
})
export class NgxMaterialPalettePickerComponent implements OnInit {

  constructor() {

  }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个types在根路径中调用的目录,并将以下代码添加到index.d.ts:

declare module '*.json' {
  const value: any;
  export default value;
}
Run Code Online (Sandbox Code Playgroud)

我还添加了目录typestypeRoots主tsconfig.json.

"typeRoots": [
  "node_modules/@types",
  "types"
],
Run Code Online (Sandbox Code Playgroud)

该项目在Sublime编辑器中没有显示任何错误,但是当我尝试使用该命令构建项目时,ng build --prod ngx-material-palette-picker我得到了本问题开头所述的错误.如何解决这个问题呢?

小智 1

JSON 文件应该放置在 Angular 知道要搜索的地方(例如“src/assets”)。您应该将 JSON 文件的路径添加到“assets”下的 angular.json,如此处答案中所述:Import json file in typescript Angular 5

或者,您可以通过 http 请求获取 JSON 文件的内容。但我相信上述方法在这种情况下仍然适用。