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 ';'
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.
精彩评论