0

I build Angular Universal (SSR) application. Now I installed package for express server. Inside that package there are lines like that:

require(./package) -> this doesn't work (angular can't resolve it) because angular expects to require it like require(./package.json)

require(../folderdir) -> this doesn't work (angular can't resolve it) because angular expects to require it like require(../folderdir/index.json)

How can I tell angular universal to also resolve .json extensions?

P.S. I use angular cli and I don't have webpack config file to modify.

O. Shekriladze
  • 1,346
  • 1
  • 19
  • 36

1 Answers1

0

Step:1-Update your package.json so that you can use fs module on client side browser npm-package.json

"browser": {
    "fs": false,
    "os": false,
    "path": false
  }

Reference

Use fs module to read .json file

import {Observable} from "rxjs/Observable";
 import {TranslateLoader} from '@ngx-translate/core';
          
  declare var require: any;
  import {join} from 'path';
      
  const fs = require('fs');
      
  export class Loader {
      
    getJson(){

   const assets_folder = join(process.cwd(), 'dist', 'server', this.prefix);
  const jsonData = JSON.parse(fs.readFileSync(`${assets_folder}/${lang}${this.suffix}`, 'utf8'));

  return jsonData;
 }
}

More Information on importing json with SSR

or you can import entire json file directly

import * as indexJSON from 'assets/index.json';


use indexJSON where ever you want.

or

add file typings.d.ts to the project's root folder with below content

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

and then import your data like this:

import * as data from './example.json';

update July 2019:

Typescript 2.9 ([docs][2]) introduced a better, smarter solution. Steps:

  1. Add resolveJsonModule support with this line in your tsconfig.json file:
"compilerOptions": {
    ...
    "resolveJsonModule": true
  }

the import statement can now assumes a default export:

import data from './example.json';
Credit

Vikas
  • 11,859
  • 7
  • 45
  • 69