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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41467801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:08:16  来源:igfitidea点击:

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

typescriptconfiguration-files

提问by r0estir0bbe

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

我正在使用 TypeScript 开发一个 Web 应用程序。对于应用程序的某些部分,我想定义一个简单的配置文件来指定某些方面(例如调色板)。

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

我将如何创建这样的配置文件?在 JavaScript 中,config.js在 HTML 代码中创建和引用它是一个非常简单的解决方案。TypeScript 的最佳解决方案是什么?也许是一个单独的Config.ts文件?

采纳答案by HolgerJeromin

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

由于 Typescript 被转换为 JavaScript,因此您的用例没有区别。浏览器获取的不是 TS 代码,而是 JS。

回答by Amid

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');

回答by Stéphane Veyret

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 confinodepackage which fully manages the configuration file for you.

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