Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import json from my angular library component

Here is the repository in Github if you want to help me to check what is happening: https://github.com/sandrocsimas/ngx-material-palette-picker

I'm trying to create my first angular library. I generated the code by using angular cli commands:

ng new ngx-material-palette-picker-app
ng generate library ngx-material-palette-picker

In the component NgxMaterialPalettePickerComponent I'm importing a json file, but the build is throwing the following error:

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

This is my component:

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

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

  constructor() {

  }
}

I created a directory called types in the root path and added the following code to index.d.ts:

declare module '*.json' {
  const value: any;
  export default value;
}

I also added the directory types to typeRoots in the main tsconfig.json.

"typeRoots": [
  "node_modules/@types",
  "types"
],

The project don't show any error in Sublime editor, but when I try to build the project using the command ng build --prod ngx-material-palette-picker I get the error described in the beginning of this question. How to solve this problem?

like image 641
Sandro Simas Avatar asked Jul 12 '18 19:07

Sandro Simas


1 Answers

The JSON file should be placed somewhere angular knows to search (e.g. 'src/assets'). You should add the path to you JSON files to your angular.json under 'assets' as described in the answer here: Import json file in typescript Angular 5

Alternatively you could get the contents of the JSON file with an http request. Though I believe the above method still applies in that case.

like image 84
Gunnaway Avatar answered Oct 20 '22 23:10

Gunnaway