简体   繁体   English

如何为 TypeScript 创建特定于应用程序的配置文件?

[英]How to create an application-specific config file for TypeScript?

I am working on a web application using TypeScript.我正在使用 TypeScript 开发一个 Web 应用程序。 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.在 JavaScript 中,创建config.js并在 HTML 代码中引用它是一个非常简单的解决方案。 What would be the best solution for TypeScript? TypeScript 的最佳解决方案是什么? Maybe a separate Config.ts file?也许是一个单独的Config.ts文件?

You can do it the following way.您可以通过以下方式进行。

First define structure of your config file, in lets say config.ts:首先定义配置文件的结构,比如 config.ts:

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

Then create config.json that actually holds the data:然后创建实际保存数据的 config.json:

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

And consume it in your app.ts:并在您的 app.ts 中使用它:

let config: Config = require('./path/to/config.json');

As Typescript is transpiled into JavaScript there is no difference in your usecase.由于 Typescript 被转换为 JavaScript,因此您的用例没有区别。 The browser does not get the TS code but the JS.浏览器获取的不是 TS 代码,而是 JS。

我知道这是一个旧线程,但是对于在 Google 搜索(并寻找完整解决方案)后到达这里的人来说,有一个confnode包可以为您完全管理配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM