问题
Here is my dilemna:
I am a noob (currently interning and helping to maintain two e-commerce sites) at javascript. I was recently assigned to remove all the comments that occur in our javascript libraries (which is over 25,000 comments!). Obviously I want to find a function or some pre-existing program that can parse through the code, removing all characters following // or */...
I have looked into some minifiers available online such as Yui, jscompressor.com, and uglifyJS that would make this task more automated, but there are a few problems. Either they are too aggressive (shortening variable names, removing all whitespace, etc.) or they require that you feed one line or one file at a time. I am dealing with literally 1000s of .js files.
Additional details: our development environment is Eclipse IDE and xammp; languages are html, php, css.
Any recommendations of a program that can fit my needs would be great!
回答1:
Take a closer look at uglifyjs. It neither compresses nor munges by default (you have to give the -c and -m options, respectively), and you can choose in fine detail what kinds of compression it does, even to the level of specifying a regular expression for what kinds of comments to remove. And, you can even pretty print on the way out, if you're so inclined. So what's the problem with using it?
回答2:
I know this question is a few years old - but all the Javascript comment strippers I found couldn't handle the 2.6mb Javascript file I was trying to strip.
I created a jsfiddle with the following code, then pasted the 2.6mb file into the textbox and it worked for me:
$("textarea").val($("textarea").val().replace(/\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\//g,"")); /*remove these comment types*/
$("textarea").val($("textarea").val().replace(/\/\/.*/g,"")); // remove these comment types
https://jsfiddle.net/40okonqo/
Hope it helps someone.
Credit: I used information found here to help with the regular expression: http://blog.ostermiller.org/find-comment
回答3:
In fact, it is not that easy to build a regexp that removes all comments from a javascript document.
The basic solution is to use :
yourJavascriptString.replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '');
Unfortunately it does not always works. If you need a more complete solution, please visit this website : http://james.padolsey.com/javascript/removing-comments-in-javascript/
来源:https://stackoverflow.com/questions/10403098/looking-to-remove-comments-from-a-large-amount-of-javascript-files