有没有一种快速的工具可以在不剥离JavaScript源代码中的注释的情况下执行恒定的替换?

Is there any fast tool which performs constant substitution without stripping out comments in JavaScript source code?

本文关键字:源代码 JavaScript 剥离 注释 情况下 替换 执行 一种 工具 有没有      更新时间:2023-09-26

例如,设置MYCONST = true将导致

的转换
 if (MYCONST) {
     console.log('MYCONST IS TRUE!'); // print important message
 }

 if (true) {
     console.log('MYCONST IS TRUE!'); // print important message
 }
这个工具最好有一个快速的node.js API。

一个更好的方法来实现你想要的-

Settings.js

 settings = {
   MYCONST = true
 };

MainCode.js

 if (settings.MYCONST) {
     console.log('MYCONST IS TRUE!'); // print important message
 }

google的闭包编译器,除其他事项外,内联的常量注释时,留下字符串内容不变,但我不确定这是否是一个可行的选择,为您

修补美化器,例如

  • 获取JS美化器https://raw.github.com/einars/js-beautify/master/beautify.js。
  • function print_token()的最后一行替换为

    output.push (token_text = ="MYCONST"?"真正的":token_text);

  • 从nodejs内部调用js_beautify(your_code)

Apache Ant构建系统支持一个可用于实现此目的的替换任务。

Edit:哎呀。先看标题。忽略我。

Google Closure Compiler有这样一个特性:

您可以将代码中的@define标记与--define参数结合起来,在"编译"时更改变量。

闭包编译器也会删除你的if语句,这可能是你想要的。

简单地这样写代码:

/** @define {boolean} */
var MYCONST = false; // default value is necessary here
if (MYCONST) {
    console.log('MYCONST IS TRUE!'); // print important message
}

并使用参数

调用编译器
java -jar closure-compiler.jar --define=MYCONST=true --js pathto/file.js

关于你的API请求:闭包编译器有一个JSON API