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

寵の児 提交于 2019-12-11 02:53:57

问题


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.


回答1:


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.




回答2:


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.




回答3:


Patch a beautifier, for example

  • Get the JS Beautifier https://raw.github.com/einars/js-beautify/master/beautify.js written in JS.
  • Replace the last line of function print_token() by something like

    output.push(token_text=="MYCONST"?"true":token_text);

  • Call js_beautify(your_code) from within nodejs.



回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/8582798/is-there-any-fast-tool-which-performs-constant-substitution-without-stripping-ou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!