Is there any fast tool which performs constant sub

2019-07-16 14:26发布

For example, setting MYCONST = true would lead to the transformation of

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

to

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

This tool ideally has a fast node.js accessible API.

5条回答
霸刀☆藐视天下
2楼-- · 2019-07-16 14:37

Edit: Whoops. Gotta read title first. Ignore me.

Google Closure Compiler has such a feature:

You can combine the @define tag in your code with the --define parameter to change variables at "compile" time.

The closure compiler will also remove your if-statement, which is probably what you want.

Simply write your code like this:

/** @define {boolean} */
var MYCONST = false; // default value is necessary here

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

And call the compiler with the parameter:

java -jar closure-compiler.jar --define=MYCONST=true --js pathto/file.js

Regarding you API request: Closure Compiler has a JSON API.

查看更多
smile是对你的礼貌
3楼-- · 2019-07-16 14:42

The Apache Ant build system supports a replace task that could be used to achieve this.

查看更多
虎瘦雄心在
4楼-- · 2019-07-16 14:57

Patch a beautifier, for example

查看更多
Emotional °昔
5楼-- · 2019-07-16 14:58

google's closure compiler does, among other things, inlining of constants when annotated as such, leaving string content untouched but I am not sure if it's a viable option for you.

查看更多
老娘就宠你
6楼-- · 2019-07-16 14:58

A better way to achieve what you want -

Settings.js

 settings = {
   MYCONST = true
 };

MainCode.js

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

This way, you make a change to one single file.

查看更多
登录 后发表回答