Sunil Kumar Sahu
Sunil Kumar Sahu

Reputation: 1515

BUILD ERROR - Unexpected token / in JSON at position 0

I have created a angular library named ng-common-lib. Created a component in side library which reads contents from a json file.

jsonFile.json

{
    "name" : "Sunil"
}

Below code to read json file in my component.

import * as jsonFile from '../../../assets/jsonFile.json';
.....
ngOnInit() {
    console.log(jsonFile); 
}

Added below two lines to tsconfig.json to read data from json file.

"resolveJsonModule": true,
"esModuleInterop": true,

Then I have ran ng build ng-common-lib command to generate build, but it got failed with below error.

users-iMac:ng-ui-library user$ ng build ui-components
Building Angular Package
Building entry point '@ui/components'
Compiling TypeScript sources through ngc
Bundling to FESM2015

BUILD ERROR
Unexpected token / in JSON at position 0
SyntaxError: Unexpected token / in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.transform (/Users/vasu/Desktop/Sunil/Practice/ng-ui-lib/node_modules/rollup-plugin-json/dist/rollup-plugin-json.cjs.js:18:20)
    at /Users/vasu/Desktop/Sunil/Practice/ng-ui-lib/node_modules/rollup/dist/rollup.js:20962:25
    at <anonymous>

Please help to solve this issue.

Upvotes: 2

Views: 1663

Answers (2)

Nick Cox
Nick Cox

Reputation: 31

I can confirm setting annotateForClosureCompiler to false in tsconfig.lib.json fixed this for me.

Upvotes: 3

user4851087
user4851087

Reputation:

You need to read the json file content using http So first you need to create a service to fetch the json content

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable';
import { Injectable } from "@angular/core";

@Injectable()
export class JsonSettingService {
  constructor(private http: HttpClient) {
  }

   public getJsonData(): Observable<any> {
    return this.http.get("./assets/jsonFile.json");
  }
}

Then inject your service into your component

export class MyComponent implements OnInit {
    constructor(
        private jsonSettingService : JsonSettingService  
    ) { }

   ngOnInit(){
       this.jsonSettingService.getJsonData().subscribe(data => {
            console.log(data);
        });
   }
}

Please let me know if you need any help.

Upvotes: 1

Related Questions