24

I am working on a web application using TypeScript. For some parts of the application, I would like to define a simple configuration file that specifies certain aspects (for example the color palette).

How would I create such a configuration file? In JavaScript, creating config.js and referencing it in the HTML code is a very simple solution. What would be the best solution for TypeScript? Maybe a separate Config.ts file?

r0estir0bbe
  • 699
  • 2
  • 7
  • 23

3 Answers3

59

You can do it the following way.

First define structure of your config file, in lets say config.ts:

export interface Config
{
    uriPath: string;   
    port: number;   
    settings: string[];
}

Then create config.json that actually holds the data:

{
    "uriPath": "mgNation",
    "port": 1506,
    "settings": [
        "=[tor.start]",
        "=[copp.start]"
    ]
}

And consume it in your app.ts:

let config: Config = require('./path/to/config.json');
Amid
  • 21,508
  • 5
  • 57
  • 54
  • 1
    I think that in the interface 'Config', you cannot use the public modifier, it should just be `uriPath: string;` etc. Thanks for the approach though! – actual_kangaroo Jan 09 '18 at 03:46
7

As Typescript is transpiled into JavaScript there is no difference in your usecase. The browser does not get the TS code but the JS.

HolgerJeromin
  • 2,201
  • 20
  • 21
0

I know this is an old thread, but for people arriving here after a Google search (and looking for a full solution), there is the confinode package which fully manages the configuration file for you.

Stéphane Veyret
  • 1,791
  • 1
  • 8
  • 15
  • 3
    I think for people looking for an answer to this, it's not a good idea to resort to a package. I want to know how to do this properly. If I use a package I'm not learning anything – o-az Aug 18 '21 at 20:23