简体   繁体   English

声明全局调试变量

[英]Declare global debug variable

I'd like to import and use the following function for debugging: 我想导入并使用以下功能进行调试:

export function debug(string) {
  if(debugMode) { console.log(`DEBUG: ${string}`) }
}

but I don't know how to make a variable, like debugMode globally accessible. 但我不知道如何使变量(例如debugMode全局访问。 Is this even possible with TypeScript? 使用TypeScript甚至可能吗? I would simply set it in app.component.ts to true or false so the function only works when I need it. 我只是将app.component.ts它设置为truefalse所以该功能仅在需要时才起作用。

You could do it that way 你可以那样做

utils.module.ts utils.module.ts

export class Config
{
  constructor(public readonly debugMode) {  }
}
export let GlobalConfig  = new Config(true);

export function debug(string) {
  if(GlobalConfig.debugMode) { console.log(`DEBUG: ${string}`); }
}

Your component 您的组件

import {debug, GlobalConfig} from '../utils.module';
//..
debug('test');
if(GlobalConfig.debugMode)
    console.log('In debug mode');

You just need to import that function and the conf variable when you need to use it 您只需要在使用它时导入该函数和conf变量即可

If you just export and import debugMode , any class can modify it (not sure if it's what you want) 如果仅导出和导入debugMode ,则任何类都可以对其进行修改(不确定是否是您想要的)

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

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