tags:

views:

103

answers:

4

I have a minified/packed javascript file which is causing problems. The issue is that the non-packed input file has some missing semicolons somewhere which aren't a problem when there's line breaks, but when the file is packed, the line breaks are removed and that causes a parser error. For example:

//input
var x = function() {
    doSomething();
}  // note: no semicolon
var y = 'y';

//----
// output
var x=function(){doSomething();}var y='y';
//                  error here: ^

The strange thing is that when I do a replace on the output file to replace all semicolons with a semicolon and a new line, the file works! This is making it ludicrously hard to find the error, since AFAIK, I can't think of any situation where a line break after a semicolon should change anything. Any ideas about why doing this replace would make it work?

+4  A: 

Uh... Have you tried JSLint?

Shog9
it hurt my feelings.
nickf
Damn you Doug Crockford!
ichiban
to explain: running the non-packed file through JSLint and wading through the errors to find missing semicolons solved the problem. I'm still confused about why it worked when adding the linebreaks after semicolons though...
nickf
Beats me. Life's too short... but i guess if you get bored enough to figure it out by hand, you could come back and sate our idle curiosity! ;-)
Shog9
+3  A: 

When there's a line break, there's an implied semi-colon.

ichiban
yes i know. The only linebreaks in the file are now directly following a semicolon, so it should need to imply anything, and it's working.
nickf
+1  A: 

Use jslint to check your code. If you do this and get it passing with regards to semicolons, it should pack correctly.

In JavaScript, semicolons are implicitly added at newlines. This introduces situations that can be ambiguous. This blog post: http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/ describes the problem succinctly and gives an example.

artlung
+1  A: 

JSlint is a good solution. Also, some code editors will find these kinds of errors for you. If I recall correctly, NetBeans catches these in realtime, as you type. I believe Komodo and Aptana do as well.

Nosredna
Also IntelliJ IDEA does so.
Svitlana Maksymchuk