1

I have a config file. I added the file to .gitignore because it will be different based on the environment.

In some environments, the file might not be existing. In this case, I will use default values. So want to import a JSON file if it exists. I can import JSON file easily like import config from 'config.json';

When the file does not exist, it says: "Cannot find module 'config.json'."

I'm using angular 8, typescript.

canbax
  • 3,432
  • 1
  • 27
  • 44
  • you should create sampleConfig.josn and no need to add it to .gitignore file and still config.json should be gitignore. and every where use this project just need to rename it to config.json. – Roohbakhsh Masoud Nov 18 '19 at 11:57
  • You can look this: [How to test if a string is JSON or not? ](https://stackoverflow.com/a/9804835/2468781) – eildiz Nov 18 '19 at 11:55
  • I think this question is not a duplicate question but the recommended method in the question solves my issue. – canbax Nov 18 '19 at 15:25

1 Answers1

0

Don't add config.json to the .gitignore file as you need this file to compile the source code. You can use Angular's "fileReplacements" feature for configuring different build environments.

https://angular.io/guide/build#configure-target-specific-file-replacements

You would create two files.

config.prod.json:

{ example: "Some data" }

config.json:

false

You then configure Angular to copy config.prod.json during production builds only.

"configurations": {
"production": {
    "fileReplacements": [
        {
            "replace": "src/config.json",
            "with": "src/config.prod.ts"
        }
    ],

You can now import this file, but for developer builds it will yield Boolean(false) and for production it will be a truthy value.

import config from 'config.json';

if(config) {
   console.log("Config for production");
} else {
   console.log("There is no config, then use something else");
}
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • thanks for the answer but your answer is valid If I have only 2 environments. Instead of that using approaches stated in https://stackoverflow.com/questions/47206924/angular-5-service-to-read-local-json-file are more flexible – canbax Nov 18 '19 at 12:23