我有一个typescript项目,其中有一堆只创建调试信息的代码。在分析了我的应用程序后,发现这些代码对性能有很大的影响。
我目前的方法是设置一个全局变量let debug=true
,并且
function log(statement: string):void {
if(debug) console.log(statement);
}
// somewhere in the application
...
log(`hi mom! ${Factory.createDebugStatement()}`);
...
这个Factory.createDebugStatement()
的计算量很大,而且我希望避免if(debug) log(...)
使我的应用程序变得混乱,我希望typescript删除整个日志语句。
基本上,我在下面的C
结构中寻找一个(方便的)TS
"等价物":
// header file
#ifdef ENABLE_DEBUG
#define DEBUG(...) printf(__VA_ARGS__)
#else
#define DEBUG(...) \
{}
#endif
//application
main(){
...
DEBUG("hi mom!");
...
}
然后,我可以使用cc -DENABLE_DEBUG=1 main.c
来获得这些调试消息,如果我省略-DENABLE_DEBUG
,整个代码将被删除。
2条答案
按热度按时间d5vmydt91#
为此,我通常会使用具有“Tree-shaking”功能的捆绑器,例如https://esbuild.github.io/api/#tree-shaking或https://parceljs.org/features/scope-hoisting/
在esbuild中,这相对容易:https://esbuild.github.io/api/#define
您定义了
debug
变量 *,捆绑器会自动删除从未执行过的代码分支。DEBUG_YOUR_PACKAGE_NAME
,这样不太可能与依赖项中的代码冲突)a14dhokn2#
信用:感谢Simon Lax指示我专注于bundler部分...
我正在使用rollup.js,带有plugin-strip插件。然后,用我的
rollup.config.js
中的一个开关,我可以启用/禁用"transpile away"那么在运行
npm run bundle
之后,它将创建剥离的版本并运行
DEBUG=1 npm run bundle
,它将创建完整版本(for完整性,我的
tsconfig.json
)