1

I want to compress js files and convert into single line at the time of loading using php.when I removes the spaces with 'preg_replace' an error occurs, ';' missing in line 234. The cause is some lines are not ending with ';'.For eg

          var flag='value'  // here not ended with ';'
          var test='value';

And when I minifies, it looks like

          var flag='value' var test='value';

So error occurs.

How can I minify js files with some lines not ending with ';'

ajay
  • 343
  • 2
  • 8
  • 16
  • 3
    make them all end with ; if needed and remember to remove all comments – mplungjan Mar 31 '11 at 06:16
  • @corroded I've never seen IE do that. – alex Mar 31 '11 at 06:19
  • cry like a baby? good for you sir – corroded Mar 31 '11 at 06:26
  • @corroded: neither have I. All browsers will fail if the JS is minified with lacking semicolons. The one thing that makes IE cry and Fx not are trailing commas in object lists `{ "a":1, "b":2,}` – mplungjan Mar 31 '11 at 06:40
  • that too. i also get those trailing comma failures. but i do remember at one point that it cried just because of a missing semi-colon. or maybe of the console.log..which was incidentally missing a semi-colon. mmm. in any case, ie is a cry baby – corroded Mar 31 '11 at 06:41

1 Answers1

1

You would want to use a real parser based on the rules for automatic semi colon insertion.

Otherwise if you do (i.e. use a regex)...

$str = preg_replace('/(?<!;)\s*(\n|\z)/', ";$1", $str);

...you are going to munch valid JavaScript, e.g.

var a = 'a',
    b = 'bob';

...which will become...

var a = 'a',;
    b = 'bob';

CodePad.

There are plenty of existing JavaScript packers/minifiers.

Community
  • 1
  • 1
alex
  • 438,662
  • 188
  • 837
  • 957