debugging 如何“传送”日志语句

cedebl8k  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(95)
    • bounty将在6天后过期**。回答此问题可获得+50声望奖励。Joel希望引起更多人对此问题的关注:我想听听Maven的意见,如果我们什么都没找到,我们可以创建一个TS功能请求.

我有一个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,整个代码将被删除。

d5vmydt9

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,这样不太可能与依赖项中的代码冲突)
a14dhokn

a14dhokn2#

信用:感谢Simon Lax指示我专注于bundler部分...
我正在使用rollup.js,带有plugin-strip插件。然后,用我的rollup.config.js中的一个开关,我可以启用/禁用"transpile away"

// src/main.ts
import fs from "fs";
class Service {
  expensive(res = ""): string {
    for (let i = 0; i < 1000; i++) res += i;
    return res;
  }
  normal(): string {
    return "Hi mom!";
  }
}

class Logger {
  public static log<T>(statement: T): T | undefined {
    console.log(statement);
    return statement;
  }
}

const s = new Service();

Logger.log(`${s.expensive()}`);

console.log(s.normal());

// and I can even use it in different situations, which usually expect the output.
fs.writeFileSync(
  "/tmp/abc",
  Logger.log(
    "not printed to screen nor to file but I wont have runtime exceptions, because TS hints me to catch the undefined case with the null'ish concealing",
  ) ?? "",
);
// rollup.config.js
import typescript from "@rollup/plugin-typescript";
import strip from "@rollup/plugin-strip";

export default [
  {
    external: ["fs"],
    input: ["src/main.ts"],
    output: {
      dir: "dist",
      format: "es",
    },
    strictDeprecations: true,
    plugins: [
      strip({
        include: ["**/*.ts"],
        functions: process.env.DEBUG ? [] : ["logger.log"],
      }),
      typescript(),
    ],
  },
];
// package.json
 
 "type": "module",
  "scripts": {
    "bundle": "rollup --config rollup.config.js"
  },
  "devDependencies": {
    "@rollup/plugin-strip": "^3.0.2",
    "@rollup/plugin-typescript": "^11.0.0",
    "rollup": "^3.15.0",
    "typescript": "^4.9.5"
  },

那么在运行npm run bundle之后,它将创建剥离的版本

// dist/main.js
import fs from 'fs';

class Service {
    expensive(res = "") {
        for (let i = 0; i < 1000; i++)
            res += i;
        return res;
    }
    normal() {
        return "Hi mom!";
    }
}
const s = new Service();
console.log(s.normal());
// and I can even use it in different situations, which usually expect the output.
fs.writeFileSync("/tmp/abc", "");

并运行DEBUG=1 npm run bundle,它将创建完整版本

// dist/main.js
import fs from 'fs';

class Service {
    expensive(res = "") {
        for (let i = 0; i < 1000; i++)
            res += i;
        return res;
    }
    normal() {
        return "Hi mom!";
    }
}
class Logger {
    static log(statement) {
        console.log(statement);
        return statement;
    }
}
const s = new Service();
Logger.log(`${s.expensive()}`);
console.log(s.normal());
// and I can even use it in different situations, which usually expect the output.
fs.writeFileSync("/tmp/abc", Logger.log("not printed to screen nor to file but I wont have runtime exceptions, because TS hints me to catch the undefined case with the null'ish concealing") ?? "");

(for完整性,我的tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "outDir": "dist",
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "baseUrl": "."
  },
  "ts-node": {
    "transpileOnly": true
  }
}

相关问题