25

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?

1
  • A separate config.ts file seems fine. Commented Jan 4, 2017 at 17:12

3 Answers 3

62

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');
Sign up to request clarification or add additional context in comments.

1 Comment

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!
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.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.