Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import JSON file to Angular library?

I'm having trouble importing JSON file to my environment file in Angular 7 library. My environment.ts file looks like this:

import firebase from './firebase.json';

export const environment = {
  production: false,
  firebase,
};

And firebase.json:

{
  "apiKey": "",
  "authDomain": "",
  "databaseURL": "",
  "projectId": "",
  "storageBucket": "",
  "messagingSenderId": ""
}

But unfortunately when running ng build it fails:

> [email protected] build <path-to-project>/sdk
> ng build sdk

Building Angular Package
Building entry point 'sdk'
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 (<path-to-project>/sdk/node_modules/rollup-plugin-json/dist/rollup-plugin-json.cjs.js:18:20)
    at <path-to-project>/sdk/node_modules/rollup/dist/rollup.js:20962:25

Unexpected token / in JSON at position 0
SyntaxError: Unexpected token / in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.transform (<path-to-project>/sdk/node_modules/rollup-plugin-json/dist/rollup-plugin-json.cjs.js:18:20)
    at <path-to-project>/sdk/node_modules/rollup/dist/rollup.js:20962:25
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `ng build sdk`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     xxx/.npm/_logs/2019-04-10T13_40_47_486Z-debug.log

I've tried already:

1) Adding to tsconfig.json

"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,

2) Adding typings.d.ts with

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

3) Changing import to require

But no luck so far.

My devDependencies include:

"@angular-devkit/build-ng-packagr": "^0.13.8",
"@angular/cli": "~7.3.6",
"@angular/common": "~7.2.0",
"@angular/compiler": "^7.2.12",
"@angular/compiler-cli": "^7.2.12",
...
like image 271
Gerda Avatar asked Feb 03 '23 19:02

Gerda


1 Answers

After a lot of suffering we found that solution here.

It's basically what you've done in the first try, but you need to add one option more.

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

Additionally:

"annotateForClosureCompiler": false

Note: for the last prop, that's the same file but instead of adding it to the compilerOptions, add it to angularCompilerOptions

like image 139
Radek Konrad Furmański Avatar answered Feb 06 '23 09:02

Radek Konrad Furmański