Giter VIP home page Giter VIP logo

matthiasmullie / minify Goto Github PK

View Code? Open in Web Editor NEW
1.9K 78.0 307.0 897 KB

CSS & JavaScript minifier, in PHP. Removes whitespace, strips comments, combines files (incl. @import statements and small assets in CSS files), and optimizes/shortens a few common programming patterns.

Home Page: https://matthiasmullie.github.io/minify/

License: MIT License

PHP 86.86% Makefile 0.56% CSS 0.77% JavaScript 11.47% Dockerfile 0.33%
minify minifier php javascript css css-minifier js-minifier compressor compression js

minify's Introduction

Minify

Build status Code coverage Latest version Downloads total License

Removes whitespace, strips comments, combines files (incl. @import statements and small assets in CSS files), and optimizes/shortens a few common programming patterns, such as:

JavaScript

  • object['property'] -> object.property
  • true, false -> !0, !1
  • while(true) -> for(;;)

CSS

  • @import url("http://path") -> @import "http://path"
  • #ff0000, #ff00ff -> red, #f0f
  • -0px, 50.00px -> 0, 50px
  • bold -> 700
  • p {} -> removed

And it comes with a huge test suite.

Usage

CSS

use MatthiasMullie\Minify;

$sourcePath = '/path/to/source/css/file.css';
$minifier = new Minify\CSS($sourcePath);

// we can even add another file, they'll then be
// joined in 1 output file
$sourcePath2 = '/path/to/second/source/css/file.css';
$minifier->add($sourcePath2);

// or we can just add plain CSS
$css = 'body { color: #000000; }';
$minifier->add($css);

// save minified file to disk
$minifiedPath = '/path/to/minified/css/file.css';
$minifier->minify($minifiedPath);

// or just output the content
echo $minifier->minify();

JS

// just look at the CSS example; it's exactly the same, but with the JS class & JS files :)

Methods

Available methods, for both CSS & JS minifier, are:

__construct(/* overload paths */)

The object constructor accepts 0, 1 or multiple paths of files, or even complete CSS/JS content, that should be minified. All CSS/JS passed along, will be combined into 1 minified file.

use MatthiasMullie\Minify;
$minifier = new Minify\JS($path1, $path2);

add($path, /* overload paths */)

This is roughly equivalent to the constructor.

$minifier->add($path3);
$minifier->add($js);

minify($path)

This will minify the files' content, save the result to $path and return the resulting content. If the $path parameter is omitted, the result will not be written anywhere.

CAUTION: If you have CSS with relative paths (to imports, images, ...), you should always specify a target path! Then those relative paths will be adjusted in accordance with the new path.

$minifier->minify('/target/path.js');

gzip($path, $level)

Minifies and optionally saves to a file, just like minify(), but it also gzencode()s the minified content.

$minifier->gzip('/target/path.js');

setMaxImportSize($size) (CSS only)

The CSS minifier will automatically embed referenced files (like images, fonts, ...) into the minified CSS, so they don't have to be fetched over multiple connections.

However, for really large files, it's likely better to load them separately (as it would increase the CSS load time if they were included.)

This method allows the max size of files to import into the minified CSS to be set (in kB). The default size is 5.

$minifier->setMaxImportSize(10);

setImportExtensions($extensions) (CSS only)

The CSS minifier will automatically embed referenced files (like images, fonts, ...) into minified CSS, so they don't have to be fetched over multiple connections.

This methods allows the type of files to be specified, along with their data:mime type.

The default embedded file types are gif, png, jpg, jpeg, svg, apng, avif, webp, woff and woff2.

$extensions = array(
    'gif' => 'data:image/gif',
    'png' => 'data:image/png',
);

$minifier->setImportExtensions($extensions);

Installation

Simply add a dependency on matthiasmullie/minify to your composer.json file if you use Composer to manage the dependencies of your project:

composer require matthiasmullie/minify

Although it's recommended to use Composer, you can actually include these files anyway you want.

License

Minify is MIT licensed.

minify's People

Contributors

alexcorvi avatar annoyingtechnology avatar catrope avatar enricodias avatar ginopane avatar gordonlesti avatar groupm-mbuella avatar igll avatar k3min avatar kaittodesk avatar matthiasmullie avatar mattleff avatar merty avatar roccohoward avatar roggeo avatar rozinko avatar rv7pr avatar simondud avatar smxsm avatar stklcode avatar summercms avatar tabrisrp avatar techteam-seobility avatar throup avatar timhunt avatar vladimmi avatar woutervanvliet avatar xerc avatar zebratrois avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

minify's Issues

Negative numbers bug

Hi,
you've done a great job. 1 bug and 1 issue, though.

  1. Minification error. The following code:
    { background-position: -0px- 64px; }
    becomes:
    {background-position:-0px-64px}
    which is interpreted wrong by a browser. I'm not sure if it's only for negative numbers, or not. Anyway, it should be:
    {background-position:-0px -64px}
  2. Couldn't files from the data/js folder be written to the PHP file as a constant/variable? It would save 4 I/O operations for creating instantions of the object. Especially since those files don't contain a lot of data.

Small strips JS comments bug

When we haven't any commens in our js files code throw exception:
"Number of elements must be positive in /minify.php on line 774"

Minifying issue in release 1.3.14

The latest release version contains an issue when minifing the CSS. And it is again a commercial project.

I'm on irc.freenode.net, username: GhaziTriki (I'm in #forkcms)

Difference in original and minified content

Tested with the latest minify version.

Original JSON http://pastebin.com/RwMTYurP
Minified JSON http://pastebin.com/YnFwQG4J

Search by "ะะฐะฟั€ัะถะตะฝะธะต ัะตั‚ะธ, ะ’":"features" in minified content โ€” it's invalid value.
Value of "ะะฐะฟั€ัะถะตะฝะธะต ัะตั‚ะธ, ะ’" must be an integer (wrapped in string). But it is minified with a value from the parent array name called features. Not always but in most cases in the example.

JS Minification generates error

I bumped into this PHP minification library and tried to check it out, But I noticed and error when trying to minify some javascripts libraries like pjax, which can be found here https://github.com/defunkt/jquery-pjax.
After checking the code, I noticed there are some statements ending without ; symbol which generates error after combination and minification.
I will be glad if this can be fixed.

@import not treated right

I am trying to minify a bunch of CSS files like so:

if(count($files))
    foreach(array_values($files) as $file)
        $minifier->add($file);

...where $files is an array of local file names (=paths, not URIs).

The first file contains a list of @imports, which are resolved the wrong way. Result is:

@import url(../P:/apache/htdocs/...more.../reset.css);

I would expect either an URL or that the imported file is read an minified too. Of course, returning an URL is not that easy, as the class would have to guess the URL from the path. (Or allow to set a BaseURL as a config param.) Anyway, better way would be to replace the imports with the minified contents of the files. Could be done quite easily by checking for local files with file_exists().

I have a workaround I got from another class (https://github.com/dg/ftp-deployment/blob/v1.1/Deployment/libs/Preprocessor.php#L63), but you may like to have a look at this. Maybe I am doing something wrong?

File Separation Whitespace

Hi Matthias,

Great script - thanks for putting it together.

I can see that the script puts the combined files in one line. I feel like separating the different files with a new line would not hurt and actually provide some insight if you have to look at the results file. What do you think about this?

CSS color minification in 1.3.9

A recent upgrade to version 1.3.9 resulted in a change of colors on our sites . A closer look showed that the following CSS:

background-color: #000000;
color: #000;

is minified to

background-color: #0;
color: #0;

which is then discarded by the following brosers (all Max OS X):

  • FireFox 34.0
  • Chrome 39.0.2171.71 (64-bit).
  • Safari 8.0 (10600.1.25.1)

Rolling back to version 1.3.8 solved the problem. At seems at least 3 digits are required:
http://www.websiteoptimization.com/speed/tweak/hex/

Sourcemaps

Are there any plans to add sourcemaps capability to minify?

Replacing while with for in JS may cause errors

Hi

I just ran into a problem with the JS minification.
It replaces 'while(true)' or similar with 'for(;;)', which breaks the code when it is a (do while).

In my case the code was :
do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}

And doesn't work when it becomes:
do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}for(;;)}

stripped ;

The minify script should take consideration when the js does not uses ";" symbols.
E.g. bootstrap does not allways use ';' characters after the code. That's why its dependend on new lines.

error: "missing ; before statement"

CSS encode base64

For some reason minifier do not encode image to base64 string only on first element with background-image property.

CSS:

.social-btn a[href*="facebook"] { background-image: url(facebook.png) } /* encode skipped */
.social-btn a[href*="vimeo"] { background-image: url(vimeo.png) }
.social-btn a[href*="instagram"] { background-image: url(instagram.png) }

PHP:

$cssMinifier = new Minify\CSS( 'styles.css' );
$cssMinifier->setMaxImportSize(10); /*  All images < 10 kb */
echo $cssMinifier->minify();

JavaScript file minification getting error

Hi there,

When I minify bootstrap.js I get the following browser error.

SyntaxError: missing ; before statement
$.fn.alert=Plugin $.fn.alert.Constructor=Alert

I have joined the original file, the minified one and a third one mifnied by http://www.jsmini.com which works when used in the project.

After comparing both compressed files it seems like the issues is coming from missing line returns between variables declarations.

Files are here : https://www.dropbox.com/sh/lwxo2pmap6z8xuu/AADc-Y1gNH493bk1qEn5UBYfa?dl=0

[QUESTION] Some small features - are they needed to PR?

Sorry if this is incorrect place to ask - don't know where to place this question :)
I've forked your minifier and added some small features for my project. They can be a bit unrelated to main goal and not so useful for others so don't know are they worth to create tests and pull request.

  1. ability to generate gzipped file near minified if path specified. So, if you call
$minifier->minify('compressed.css');

you will have two files - compressed.css (as usual) and compressed.gz.css (with gzipped content). Of course, there is setter to disable this.

  1. ability to "inline" external content into JS variables. Something similar to inlining images into CSS. My scripts use HTML files as templates for generated content. To eliminate HTTP requests you can write something like
var myTemplate = '@@import path/to/templates/file.html';

with relative path to template. Minifier will get it, slightly compress (to one line without tabs and double spaces), escape quotes (checking surround ones if they are ' or ") and insert back. So you will have something like

var myTemplate='<html><head>...</head><body>...</body></html>';

in resulting code and can load all scripts and templates with one minified and compressed file.
Import directive ("@@import") can be customized to any string.

CSS minifier deletes .0 in url string

Hi there!

I'm currently trying out your minifier which works really nice but I found a problem.
I have a CSS-File with this part:

@font-face {
  font-family: 'FontAwesome';
  src: url('//netdna.bootstrapcdn.com/font-awesome/4.2.0/fonts/fontawesome-webfont.eot?v=4.2.0');
  src: url('//netdna.bootstrapcdn.com/font-awesome/4.2.0/fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'), url('//netdna.bootstrapcdn.com/font-awesome/4.2.0/fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'), url('//netdna.bootstrapcdn.com/font-awesome/4.2.0/fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'), url('//netdna.bootstrapcdn.com/font-awesome/4.2.0/fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

In the src url there is an part 4.2.0 which is minified to 4.2 which leads to the following url:
//netdna.bootstrapcdn.com/font-awesome/4.2/fonts/fontawesome-webfont.eot?v=4.2
instead of the correct one.
shortened part of the above CSS after minification:

src:url(//netdna.bootstrapcdn.com/font-awesome/4.2/fonts/fontawesome-webfont.eot?v=4.2);

I tried this with double- and single-quotes as well as no quotes at all.
Any suggestions? For now I removed this line and it seems to work correctly: https://github.com/matthiasmullie/minify/blob/master/src/CSS.php#L370

An idea to compress CSS files a bit more

When you download the compiled Bootstrap CSS files and you try to compress it, you'll find these styles:

.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-
8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-
5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-
2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-
11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-
8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-
5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-
2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-
12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-
9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-
6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-
3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-
0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-
offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-
left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-
offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-
left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-
offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-
5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-
12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-
9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-
sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-
2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-
11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-
8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-
5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-
2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}

My guess is that if we replace X.33333333% by X.33% and X.66666667% by X.66% the result would be the same and we'll save some bytes. Is it worth it to round the numeric values with too many decimals?

Trouble minifying js script with space indeting

Hello.

I found your wonderful while searching the Interwebs. It worked really good for my CSS file. Everything was minified to one line, but I am struggling a bit with the JS-file.

It does not look like you have any support for space indenting in your compressor

I have this function:

function human_file_size(bytes, si) {
    return bytes;
};

And it is minified to:

 function human_file_size(bytes, si); {;return bytes;}

Any way you could fix this?

Problem with minimized array notation

(I thought I submitted this issue yesterday, but can not find it anymore)
It seems that
9c16060 introduces a problem with some Javascript snippets, for example: http://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/

$.extend($.expr[":"], {
    icontains: function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

is minified into

$.extend($.expr.:,{icontains:function(elem,i,match,array){return(elem.textContent||elem.innerText||"").toLowerCase().indexOf((match[3]||"").toLowerCase())>=0}});

Which breaks. Is the reduction of 4 characters (['']) really worth the potential 'trouble'?

Relative path not properly working

Received this via blog contact form. To look into.

Dear Matthias Mullie, I'm trying to use your css minifier, but I found one isue in your code with: url('../fonts/glyphicons-halflings-regular.woff) When I import fonts, your source code does not work, program replaces the relative path whith the path on the pc and not the relative path of web. For example: -Your program: -url('/var/www/example/fonts/glyphicons-halflings-regular.woff) Needed: url('serverName/pathOfFont/fonts/glyphicons-halflings-regular.woff) How I can fix this? Thank you very much for your time and your work

Missing ...0% suffix in percentage values

Hi,

I found another minification error. The following code:

.col-1-1 { width: 100.00%; }
.col-1-2 { width: 50.00%; }
.col-1-3 { width: 33.33%; } .col-2-3 { width: 66.66%; }
.col-1-4 { width: 25.00%; } .col-2-4 { width: 50.00%; } .col-3-4 { width: 75.00%; }

becomes:

.col-1-1{width:100.0}.col-1-2{width:50.0}.col-1-3{width:33.33%}.col-2-3{width:66.66%}.col-1-4{width:25.0}.col-2-4{width:50.0}.col-3-4{width:75.0}

100.00% and other round values has cutted last 0 (which is ok in this case) and % symbol (this is not ok ;)).

Webfont issue

I have a CSS file loading a Webfont like so:

@font-face {
font-family: 'blackcat';
src:url('../webfont/blackcat.eot');
src:url('../webfont/blackcat.eot?#iefix') format('embedded-opentype'),
    url('../webfont/blackcat.svg#blackcat') format('svg'),
    url('../webfont/blackcat.woff') format('woff'),
    url('../webfont/blackcat.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

Problem is, after minifying the relative URLs are not valid anymore. They should be resolved like @imports.

IE8 JavaScript minifing error

I think, JS minifier shouldn't replace this:
conf.zoomHoverIcons['default']

to:
conf.zoomHoverIcons.default

It's cause error in IE8 browser.

Using divsion in JS files messes up the minification

I found your wonderful lib and it works great, except one thing I came across with the JS minifier.

If you have multiple divisions in one script, something goes wrong.

This works fine:

function foo (a, b) {
    return a / b;
}

Minified to:

function foo(a,b){return a/b}

However, this:

function foo (a, b) {
    return a / b;
}
function foo (a, b) {
    return a / b;
}

Is minified to:

function foo(a,b){return a/b;
    }
    function foo (a, b) {
        return a / b}

Which I think is wrong.

I've fixed the problem by implementing bitwise division for now, but it would be great if you could fix this. I tried looking at your source, but I don't know anything about regex.

Use of convertRelativePath() problematic

I have my assets in src/assets/css and my minified result in web/assets/css.

Using Font Awesome as an example, I have the un-minified font-awesome.css in the first directory, and the font files in web/assets/fonts. When I use the CSS class, the convertRelativePath() method breaks all of the references to the fonts.

For my case, I fixed it by extending the CSS and overriding a method:

class MyCSS extends CSS
{
    protected function convertRelativePath($path, $from, $to)
    {
        return $path;
    }
}

I recommend adding a configuration option or method to toggle this feature on and off.

Cache?

Hi

I couldn't find any information about this.
Is the resulting file cached somehow or is the minification executed every time someone loads the page?

Thanks

Javascript compression rate

I'm glad to see a Belgian developer release his own pure PHP minification solution, but it can't compete yet with the compression rate of YUI compressor.

To test your solution, I took my code from https://github.com/jslegers/4inarow/blob/master/code.js and copy-pasted it into http://www.minifier.org/.

Before compression, the code is 3285 bytes. After compression, the code is recuded to 1908 bytes. When I compare the result with the result I get from http://refresh-sf.com/yui/, the code is reduced to 1233 bytes.

I would consider using your solution if the compression rate would be close enough to the compression rate of YUI compressor. It would also be nice to see the compression rate somewhere on the online interface and have a few configuration options, as it's done on http://refresh-sf.com/yui/ (see also #18).

To compare results, here's the output I got from my test :

Minifier

(function(doc){var start=function(){finished=false;changePlayer()},newGame=function(message){if(confirm(message)){start();forAllCells(emptyField)}},element=function(id){return doc.getElementById(id)},value=function(el){return element(el).innerHTML},cell=function(i,j){return element("c-"+i+"-"+j)},forAllCells=function(action){for(var t=1;t<7;t++){for(var counter2=1;counter2<8;counter2++){action(t,counter2)}}},sameColor=function(i,j){return testClass(i,j,players[current])},changePlayer=function(){element("c").innerHTML=players[current=(current+1)%2]},horizontalWon=function(i,j){for(var min=j-1;min>0;min--)if(!sameColor(i,min))break;for(var max=j+1;max<8;max++)if(!sameColor(i,max))break;return max-min>4},verticalWon=function(i,j){for(var max=i+1;max<7;max++)if(!sameColor(max,j))break;return max-i>3},diagonalLtrWon=function(i,j){for(var min=i-1,t=j-1;min>0;min--,t--)if(t<1||!sameColor(min,t))break;for(var max=i+1,t=j+1;max<7;max++,t++)if(t>7||!sameColor(max,t))break;return max-min>4},diagonalRtlWon=function(i,j){for(var min=i-1,t=j+1;min>0;min--,t++)if(t>7||!sameColor(min,t))break;for(var max=i+1,t=j-1;max<7;max++,t--)if(t<1||!sameColor(max,t))break;return max-min>4},colorField=function(i,j,color){cell(i,j).className=color},emptyField=function(i,j){colorField(i,j,'')},testClass=function(i,j,value){return cell(i,j).className==value},addCellBehavior=function(i,j){cell(i,j).onclick=function(j){return function(){if(!finished){for(var t=6;t>0;t--){if(testClass(t,j,'')){colorField(t,j,players[current]);if(horizontalWon(t,j)||verticalWon(t,j)||diagonalLtrWon(t,j)||diagonalRtlWon(t,j)){finished=true;newGame(wonMessage.replace("%s",players[current]))}else{changePlayer()}
break}}}}}(j)},players=[value("a"),value("b")],current=0,newGameMessage=value("n"),wonMessage=value("w"),finished;start();forAllCells(addCellBehavior);element("r").onclick=function(){newGame(newGameMessage)}})(document)

YUI Compressor

(function(t){var f=function(){i=false;g()},j=function(w){if(confirm(w)){f();l(r)}},d=function(w){return t.getElementById(w)},o=function(w){return d(w).innerHTML},b=function(x,w){return d("c-"+x+"-"+w)},l=function(y){for(var x=1;x<7;x++){for(var w=1;w<8;w++){y(x,w)}}},k=function(x,w){return h(x,w,e[n])},g=function(){d("c").innerHTML=e[n=(n+1)%2]},c=function(z,x){for(var y=x-1;y>0;y--){if(!k(z,y)){break}}for(var w=x+1;w<8;w++){if(!k(z,w)){break}}return w-y>4},u=function(y,x){for(var w=y+1;w<7;w++){if(!k(w,x)){break}}return w-y>3},s=function(A,x){for(var z=A-1,y=x-1;z>0;z--,y--){if(y<1||!k(z,y)){break}}for(var w=A+1,y=x+1;w<7;w++,y++){if(y>7||!k(w,y)){break}}return w-z>4},p=function(A,x){for(var z=A-1,y=x+1;z>0;z--,y++){if(y>7||!k(z,y)){break}}for(var w=A+1,y=x-1;w<7;w++,y--){if(y<1||!k(w,y)){break}}return w-z>4},v=function(y,x,w){b(y,x).className=w},r=function(x,w){v(x,w,"")},h=function(x,w,y){return b(x,w).className==y},q=function(x,w){b(x,w).onclick=function(y){return function(){if(!i){for(var z=6;z>0;z--){if(h(z,y,"")){v(z,y,e[n]);if(c(z,y)||u(z,y)||s(z,y)||p(z,y)){i=true;j(a.replace("%s",e[n]))}else{g()}break}}}}}(w)},e=[o("a"),o("b")],n=0,m=o("n"),a=o("w"),i;f();l(q);d("r").onclick=function(){j(m)}})(document);

Consider adding more rules to improve compression

In my current projects I use a PHP script with some simple regular expressions to compress CSS files. I copied these rules from this StackOverflow discussion.

In one of my projects, using these rules, I get a 109 KB compressed file. Using Minify for the same set of CSS files, I get a 111 KB compressed files.

I open this issue because maybe some of those rules can be applied to your project.

Spaces issue

when I have this simple function:

mn = function(x) {
  return x * x;
};

it is minified to:

mn=function(x){
return x * x};

Did spaces inside "x * x" shouldn't be removed?

Command Line Tool

Hi Matthias,

Because I need to use this on my terminal, I went ahead and build a CLI tool out of the library. You can check it out here: https://github.com/banago/CLI-Minify

It is now hard-coded, but the plan is to include it through composer or at least as a Git submodule in the future.

Hope it comes handy to somebody.

removing extra lines

Removing extra lines when try to remove commented lines in javascript

In the next code the minify delete from image/* to g.replace(/\*/g, ".*") , i think this happens when try to remove commented lines

Original

a.validator.addMethod("accept", function (b, c, d) {
    var e, f, g = "string" == typeof d ?
        d.replace(/\s/g, "").replace(/,/g, "|") :
        "image/*", h = this.optional(c);
    if (h)return h;
    if ("file" === a(c).attr("type") && (g = g.replace(/\*/g, ".*"), c.files && c.files.length))
        for (e = 0; e < c.files.length; e++)
            if (f = c.files[e], !f.type.match(new RegExp(".?(" + g + ")$", "i")))
                return !1;
    return !0
}

Minified

style="background-color:green">Mrs. Robinson</span>
a.validator.addMethod("accept", function (b, c, d) {
    var e, f, g = "string" == typeof d ?
        d.replace(/\s/g, "").replace(/,/g, "|") :
    "imageg, ". * "), c.files && c.files.length))
    for (e = 0; e < c.files.length; e++)
        if (f = c.files[e], !f.type.match(new RegExp(".?(" + g + ")$", "i")))
            return !1;
    return !0
}

Javascript error

use MatthiasMullie\Minify;

require_once 'minify/Minify.php';
require_once 'minify/JS.php';
$minifier = new Minify\JS('alert("hello")');
echo $minifier->minify();

Produces this:


Catchable fatal error: Argument 1 passed to MatthiasMullie\Minify\JS::getOperatorsForRegex() must be of the type array, boolean given, called in /var/www/xxx.com/public_html/common/minify/JS.php on line 216 and defined in /var/www/xxx.com/public_html/common/minify/JS.php on line 300

I can use the CSS minifier fine with my CSS code. Can you figure out what's going wrong?

Javascript minimize

Hi.
I have many scripts on website and add all of them to minimize. One of these scripts is jquery 2.1.0v After you libriray minimize jquery I get error.
Error:
SyntaxError: missing name after . operator
...c[b]||[]).concat(cc.*),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}fu

My minimized jquery you can find here http://nerijuso.lt/test.js

Permissions error : "The file could not be opened, check if PHP has enough permissions"

Hi,
Here is what I have :

require_once __DIR__.'/../minify/Minify.php';
require_once __DIR__.'/../minify/CSS.php';
require_once __DIR__.'/../minify/JS.php';
require_once __DIR__.'/../minify/Exception.php';
use MatthiasMullie\Minify;

$file1 = '/media/css/main.css';
$file2 = '/media/js/jquery/plugins/jquery-ui/css/jquery-ui-1.10.4.custom.min.css';
$minifier = new Minify\CSS($file1, $file2);
$minifier->minify('/media/combined.css');

When I try to combine $file1 and $file2, I have these errors :

Fatal error: Uncaught exception 'MatthiasMullie\Minify\Exception' with message 'The file "/media/combined.css" could not be opened. Check if PHP has enough permissions.' in C:\wamp\www\ariakan.core.local.net\minify\Minify.php on line 108
MatthiasMullie\Minify\Exception: The file "/media/combined.css" could not be opened. Check if PHP has enough permissions. in C:\wamp\www\ariakan.core.local.net\minify\Minify.php on line 108

What should I do ?

I'm using Wamp -> PHP 5.4.16 - Apache 2.4.4
It doesn't work ether on my server. I have no error showed, but I have this in my PHP logs :

[07-Feb-2014 15:45:08 UTC] PHP Fatal error:  Uncaught exception 'MatthiasMullie\Minify\Exception' with message 'The file "/media/combined.css" could not be opened. Check if PHP has enough permissions.' in /srv/data/web/vhosts/core.ariakan.com/htdocs/minify/Minify.php:108
Stack trace:
#0 /srv/data/web/vhosts/core.ariakan.com/htdocs/minify/CSS.php(340): MatthiasMullie\Minify\Minify->save('/media/css/main...', '/media/combined...')
#1 /srv/data/web/vhosts/core.ariakan.com/htdocs/common/functions.php(12): MatthiasMullie\Minify\CSS->minify('/media/combined...')
#2 /srv/data/web/vhosts/core.ariakan.com/htdocs/index.php(1): include('/srv/data/web/v...')
#3 {main}
  thrown in /srv/data/web/vhosts/core.ariakan.com/htdocs/minify/Minify.php on line 108

Thanks a lot ! :)

SingleLine if/else statements are breaking

Any single line if statement, is having a semi-colon attached directly after the if evaluation,

examples:

if ( !data.success )
    deferred.reject(); else
    deferred.resolve(data);

becomes

if(!data.success);deferred.reject();else;deferred.resolve(data)}

and

if ( typeof jQuery === 'undefined' )
    throw new Error('.editManager.js: jQuery is required and must be loaded first');

becomes

if(typeof jQuery==='undefined');throw new Error('.editManager.js: jQuery is required and must be loaded first');

Comments not being properly removed

Given a comment pattern like this:

// first mutation patch
// second mutation patch
// third mutation patch
// fourth mutation patch

only the fist and third comment is being removed.

Unfotunalety it gets worse, if we have something like this

/////////////////////////
// first mutation patch
// second mutation patch
// third mutation patch
// fourth mutation patch
/////////////////////////

what will result in this:

// first mutation patch
// third mutation patch
/

use minify without composer

Hey,

just a short question. Is it possible to use your Minify Application without composer?
I tried it but i don't find a way to make it work.

Thanks for your help.
Kind Regards and good night.

Consider adding configuration options

First of all, thanks for developing this project and for publishing it as open source.

I'm trying to add it to one of my projects but I'm having some problems with some of its features. I don't like things like embedding files into the CSS file. I know that I can set ->setMaxImportSize(0) but this looks hackish and I'd prefer a configuration option to disable this feature.

Another example is the rewriting of the import paths. Right now this isn't working in my case and I'd prefer not to modify the import paths. But right now the behavior cannot be modified because everything is hardcoded. Would you consider adding configuration options to enable/disable some of the compression rules? Thanks!

Small percentages values problem

Hi,

I found another bug, this CSS:

.hr > :first-child { width: 0.0001%; }

is minified to:

.hr>:first-child{width:001%}

Should be:

.hr>:first-child{width:0.0001%}

Minify::restoreExtractedData regex compilation failing

I'm getting the following error:

preg_replace_callback(): Compilation failed: regular expression is too large at offset 47638 in Minify.php on line 353

I think this is occurring because the Javascript that's being minified in this case happens to already be minified, so appears as one long line.

Unfortunately, I'm not in control of the input, so don't know when the source is already minified.

CSS is being stripped of its negative symbol.

To test, minify:

ul.pagination {
display: block;
min-height: 1.5rem;
margin-left: -0.3125rem;
}

Results in:

ul.pagination{display:block;min-height:1.5rem;margin-left:0.3125rem}

Seems the shortenZeros regex is being a little greedy and doesn't care for decimals. Temporary fix for me is changing all of "0." to just ".".

/(?<![0-9])-?0(%|px|em)?/i => matches -0.3125rem

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.