Giter Site home page Giter Site logo

jsqueeze's Introduction

JSqueeze: Efficient JavaScript minification in PHP

Latest Stable Version Total Downloads Build Status

JSqueeze shrinks / compresses / minifies / mangles Javascript code.

It's a single PHP class that has been developed, maintained and thoroughly tested since 2003 on major JavaScript frameworks (e.g. jQuery).

JSqueeze operates on any parse error free JavaScript code, even when semi-colons are missing.

In term of compression ratio, it compares to YUI Compressor and UglifyJS.

Installation

Through composer:

{
    "require": {
        "patchwork/jsqueeze": "~2.0"
    }
}

Usage

use Patchwork\JSqueeze;

$jz = new JSqueeze();

$minifiedJs = $jz->squeeze(
    $fatJs,
    true,   // $singleLine
    true,   // $keepImportantComments
    false   // $specialVarRx
);

Features

  • Removes comments and white spaces.
  • Renames every local vars, typically to a single character.
  • Keep Microsoft's conditional comments.
  • In order to maximise later HTTP compression (deflate, gzip), new variables names are choosen by considering closures, variables' frequency and characters' frequency.
  • Can rename also global vars, methods and properties, but only if they are marked special by some naming convention. Use JSqueeze::SPECIAL_VAR_PACKER to rename vars whose name begins with one or more $ or with a single _.
  • Renames also local/global vars found in strings, but only if they are marked special.
  • If you use with/eval then be careful.

Bonus

  • Replaces false/true by !1/!0
  • Replaces new Array/Object by []/{}
  • Merges consecutive var declarations with commas
  • Merges consecutive concatened strings
  • Can replace optional semi-colons by line feeds, thus facilitating output debugging.
  • Keep important comments marked with /*!...
  • Treats three semi-colons ;;; like single-line comments.
  • Fix special catch scope across browsers
  • Work around buggy-handling of named function expressions in IE<=8

To do?

  • foo['bar'] => foo.bar
  • {'foo':'bar'} => {foo:'bar'}
  • Dead code removal (never used function)
  • Munge primitives: var WINDOW=window, etc.

License

This library is free software; you can redistribute it and/or modify it under the terms of the (at your option): Apache License v2.0 (see provided LICENCE.ASL20 file), or GNU General Public License v2.0 (see provided LICENCE.GPLv2 file).

jsqueeze's People

Contributors

0b10011 avatar adamwill avatar callmemagnus avatar nicolas-grekas avatar stchr avatar stof 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

jsqueeze's Issues

Incompatibility with ECMA6

You can't use it if your javascript files have ECMAScript 6 templating with "`" character like

var name = 'Joe';
var message = `<div class="alert alert-info"> Hello ${name}</div>`;

The code generated now is:

var a='Joe';var b=`<div; class="alert alert-info"> Hello ${name}</div>`;;;

TypeError: t(...).e$.i$ is undefined

Input

this.locale = {
                applyLabel: 'Apply',
                cancelLabel: 'Cancel',
                fromLabel: 'From',
                toLabel: 'To',
                weekLabel: 'W',
                customRangeLabel: 'Custom Range',
                daysOfWeek: moment()._lang._weekdaysMin.slice(),
                monthNames: moment()._lang._monthsShort.slice(),
                firstDay: 0
            };

Expected output

;this.locale={applyLabel:'Apply',cancelLabel:'Cancel',fromLabel:'From',toLabel:'To',weekLabel:'W',customRangeLabel:'Custom Range',daysOfWeek:moment().e$.a$.slice(),monthNames:moment().e$.l$.slice(),firstDay:0};

Actual output

;this.locale={applyLabel:'Apply',cancelLabel:'Cancel',fromLabel:'From',toLabel:'To',weekLabel:'W',customRangeLabel:'Custom Range',daysOfWeek:moment()._lang._weekdaysMin.slice(),monthNames:moment()._lang._monthsShort.slice(),firstDay:0};

example https://github.com/dangrossman/bootstrap-daterangepicker/blob/master/daterangepicker.js

TypeError: n is not a function

Hi,

The following stanza from js_tpl.js is reduced in (function(){var t={};this.tmpl=function n(n,i){var p=!/\W/.test(n)?t[n]=t[n]||n(document.getElementById(n).innerHTML)::

(function () {
    var cache = {};
    this.tmpl = function tmpl(str, data) {
            // Figure out if we're getting a template, or if we need to
            // load the template - and be sure to cache the result.
            var fn = !/\W/.test(str) ?
                            cache[str] = cache[str] ||
                            tmpl(document.getElementById(str).innerHTML) :

(Hopefully the quote is enough, the full js_tpl.js is online anyway, and the fully minified JavaScript produced by JSqueeze is: (function(){var t={};this.tmpl=function n(n,i){var p=!/\W/.test(n)?t[n]=t[n]||n(document.getElementById(n).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+n.replace(/[\r\t\n]/g," ").split("<&").join("\t").replace(/((^|&>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)&>/g,"',$1,'").split("\t").join("');").split("&>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return i?p(i):p}})();;.)

The browser (well, firebug in console mode to get a hint on why the page is not properly loaded: empty content) throws TypeError: n is not a function and points to the following:

...n n(n,i){var p=!/\W/.test(n)?t[n]=t[n]||n(document.getElementById(n).innerHTML):...
    ---------------------------------------^

This breaks the ability to use the bookmark application in ownCloud with JSqueeze. Thanks in advance if you manage to fix the issue or point to a workaround.

Add invalid semicolon on multi-line for statements

I tried to use the jsqueeze lib to compress my javascript in a Symfony framework application.

The library did something strange with this:

if ( !found ) {
    for ( found = [], elems = context.childNodes || context;
        ( elem = elems[ i ] ) != null;
        i++
    ) {
        // ...
    }
}

got squeezed into this:

if(!i){for(i=[],a=t.childNodes||t;(r=a[s])!=null;s++;){/*...*/}}

Firefox (v47.0) told me then: SyntaxError: missing ) after for-loop control
Chrome (v51.0.x) told me then: Uncaught SyntaxError: Unexpected token ;

In fact the the last semicolon is too much. When I change the compressed line to:

if(!i){for(i=[],a=t.childNodes||t;(r=a[s])!=null;s++){/*...*/}}

The squeezed javascript runs fine in both browsers.

(The line is from jQuery v1.12.4 (uncompressed, line 4557)

Problem not minifying a string that starts with t single line comment

//The code below this commented line does not minify,instead is returned as a semi colon
String.prototype.compose = (function () {
var re = /{{(.+?)}}/g;
return function (o) {
return this.replace(re, function (_, k) {
return typeof o[k] !== 'undefined' ? o[k] : '';
});
};
}());

Actually code breaks if it encounters a single line comment

Invalid output from https://github.com/johnny/jquery-sortable/blob/master/source/js/jquery-sortable.js

(I'll be able to dig through JSqueeze over the next couple days to try to submit a PR--just wanted to get this up before I forget :))

This issue is specifically here:
https://github.com/johnny/jquery-sortable/blob/master/source/js/jquery-sortable.js#L236

This generates the following (invalid) code: {if(t.group===i)t.group=d++h[t.group]=new a(t)}

Even removing the space before the increment operator, it still seemed to fail.

Not PSR-0 compliant

JSqueeze claims to be PSR-0 (in its composer.json), but it really isn't:

https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

"A fully-qualified namespace and class must have the following structure \<Vendor Name>\(<Namespace>\)*<Class Name>"

that is, at least one level of namespacing is required, a top-level 'Vendor Name'. JSqueeze is a bare class. I'm now in an argument with my downstream package reviewer because our distribution guidelines don't allow us to put libraries directly in /usr/share/php (to avoid mess and conflicts - nothing else is called JSqueeze yet, but just today I found two things called cssmin, for instance...), but if I put it in a subdirectory, nothing will be able to autoload it without patching.

jsqueeze fails to minimize ExtJS

When I attempt to minify ExtJS, I receive the following invalid code:

Ext.Date=(function(){var e,t=Date,r=/(\\.)/g,l=/([gGhHisucUOPZ]|MS)/,d=/([djzmnYycU]|MS)/,s=/\\/gi,u=/\{(\d+)\}/g,o=new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'),i=Ext.String.leftPad,a=['var me = this, dt, y, m, d, h, i, s, ms, o, O, z, zz, u, v, W, year, jan4, week1monday, daysInMonth, dayMatched,','def = me.defaults,','from = Ext.Number.from,','results = String(input).match(me.parseRegexes[{0}]);','if(results){','{1}','if(u != null){','v = new Date(u * 1000);','}

Firefox says: SyntaxError: unterminated string literal in colum 480.

Broken if/else blocks

if/else blocks get a new line character added incorrectly, causing some browsers to fails with 'Unexpected strict mode reserved word'

This input javascript
if (true) {
console.log('in if');
} else {
console.log('in else');
}

results in this minified block
;if(!0){console.log('in if')}
else{console.log('in else')}

instead of
;if(!0){console.log('in if')}else{console.log('in else')}

This was introduced by dc3c407. See also #25

name of first function after comment may disappear, when keepImportantComments=true

Example input:

/*! important comment */
function first() {}
function second() {}

When minifying this through JSqueeze with e.g. $jz->squeeze($code,true,true,false), the name of the first function after an important comment disappears (and the output actually becomes invalid javascript).

Expected output:

/*! important comment */
function first(){};function second(){};

Actual output:

/*! important comment */
function(){};function second(){};

No license text included in distributions

I'm packaging JSqueeze for Fedora. The Fedora licensing guidelines note:

"In cases where the upstream has chosen a license that requires that a copy of the license text be distributed along with the binaries and/or source code, but does not provide a copy of the license text (in the source tree, or in some rare cases, anywhere), the packager should do their best to point out this confusion to upstream. This sometimes occurs when an upstream project's only reference to a license is in a README (where they simply say "licensed under the FOO license"), on their website, or when they simply do not check a copy of the license into their Source tree. Common licenses that require including their texts with all derivative works include ASL 2.0, EPL, BSD and MIT. Packagers should point out to upstream that by not including a proper full license text, they are making it difficult or impossible for anyone to comply with their desired license terms."

I don't think you have a licensing problem per se by not including the text of the licenses, but yes, it does make it harder for people redistributing your project to comply with the terms of the license. ASL 2.0 states "You must give any other recipients of the Work or Derivative Works a copy of this License; and...", and the text of the GPLv2 itself states "You should have received a copy of the GNU General Public License along with this program".

Fails to build bootstrap.js

#41 brokes *.offset declaration in bootstrap.js:

  ScrollSpy.prototype.process = function () {
    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
    var scrollHeight = this.getScrollHeight()
    var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()

compiled:

var n=this.$scrollElement.scrollTop()+this.options.offset var a=this.getScrollHeight(),s=this.options.offset +a-this.$scrollElement.height()

regex ending interpreted as a comment

The following code gets broken on the 4th line. The ending //gi, is omitted and the next line joined likely because the parser understands it is a comment.

respond.regex = {
    media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,
    keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,
    comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,
    urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
};

Result (partial):

comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\;urls:/ (url\()['"]?([^\/\)'

getter and setter are broken with variable mangling

The following test case fails:

function(coco) {

    function Test () {
        this.coco = coco;
    }

    Test.prototype = {
        get coco() {
            return this.coco;
        },
        set coco(newValue) {
            this.coco = newValue;
        }
    }

}('coco')

because of the variable replacement.

semicolon after 'continue' statement when using label

When using the 'continue' statement is possible to specify a label:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue#Using_continue_with_a_label
but this is not squeezed properly

input:

outer: do {
      for (var i = 0; i < 10; ++i) {
        if (i > 1) { continue outer }
      }
    } while (true)

output:

;outer:do{for(var i=0;i<10;++i){if(i>1){continue;outer}}}
while(!0);

the semicolon is placed after 'continue' which makes continuing the wrong loop, the for loop instead of the do

$ sign in function parameter's name breaks JS code

Hey,

if I have a code like this:

function _initialize_widgets($where) {
    if (!isset($where)) {
        where = $("body");
    }
    $where.find("input[maxlength]").maxlength({ alwaysShow: true });
    /**
     * don't initialize select2 for the template fields
    */
    $where.find(".hasSelect2:not([name*='%IDENTIFIER%'])").select2({ width: "100%" });
    $where.find(".numericInteger").numeric(false);
    $where.find(".numericFloat").numeric(".");
}

JSqueeze compiles it to:

function e$(e){if(!isset(e)){e=$("body")};e.find("input[maxlength]").maxlength({alwaysShow:!0});e.find(".hasSelect2:not([name*='%IDENTIFIER%'])").select2({width:"100%"});e.find(".numericInteger").numeric(!1);e.find(".numericFloat").numeric(".")};

which is no valid JS :(

Maybe it's not even because of the variable name, but I get a "TypeError: e$ is not a function" error...

fails to build ICAL.js

JSqueeze fails to minify ICAL.js (https://github.com/mozilla-comm/ical.js/tree/master/build)

The error is here:

_hydratedComponentCount:0,get;name(){

It's supposed to be:

_hydratedComponentCount:0,get name(){

used code to test:

<?php

use Patchwork\JSqueeze;

require_once "src/JSqueeze.php";

$jz = new JSqueeze();

$fatJs = file_get_contents(__DIR__ . '/../ical.js-master/build/ical.js');

$minifiedJs = $jz->squeeze($fatJs);

echo $minifiedJs;

a semicolon at the first of any minified file

2 issues in this filter:

The first issue is a semicolon at first if any minified js file

The second is the filter not minimizing the js file by command assetic:dump
To minimize the file i add the prod environnement at the end of command like
Assetic:dump -e=prod

My greetings

WordPress Customizer Issue

When using WordPress customizer, I see the following error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /jsqueeze/class/JSqueeze.php on line 483

 

.

.

Problem with “const”

Hi,

The following simple test

const A = 0;

is transformed into

;const;A=0;

by JSqueeze (and thus breaks the “const” syntax), while it is properly transformed in

const A=0;

by uglifyjs.

Static strings get totally mangled

Constant strings get altered by the squeezer which isn't very desirable as these are not code to be squashed.

For example the script;

var str = 'I hope you do not wish this to correctly return !' + '}else you may get upset';

when squeezed the space will be removed from between the 'return' and the '!' and a new line added between the '}' and the 'else'. The new line being inserted into the string constant then causes the compiler to fail due to an un-terminated string.

get/set related errors with autobahn.js

More get/set related syntax errors with autobahn.js:

  // save reference to original Uint8Array set method before overwriting
  arr._set = arr.set

  // deprecated
  arr.get = BP.get
  arr.set = BP.set

compiled:

var r=i.prototype;i._augment=function(e){e.constructor=i;e._isBuffer=!0;e._set=e.set arr.get=r.get arr.set=r.set arr.write=r.write;e.toString=r.toString;e.toLocaleString=r.toString;e.toJSON=r.toJSON;e.equals=r.equals;e.compare=r.compare;e.indexOf=r.indexOf;e.copy=r.copy;e.slice=r.slice;e.readUIntLE=r.readUIntLE;e.readUIntBE=r.readUIntBE;e.readUInt8=r.readUInt8;e.readUInt16LE=r.readUInt16LE;e.readUInt16BE=r.readUInt16BE;e.readUInt32LE=r.readUInt32LE;e.readUInt32BE=r.readUInt32BE;e.readIntLE=r.readIntLE;e.readIntBE=r.readIntBE;e.readInt8=r.readInt8;e.readInt16LE=r.readInt16LE;e.readInt16BE=r.readInt16BE;e.readInt32LE=r.readInt32LE;e.readInt32BE=r.readInt32BE;e.readFloatLE=r.readFloatLE;e.readFloatBE=r.readFloatBE;e.readDoubleLE=r.readDoubleLE;e.readDoubleBE=r.readDoubleBE;e.writeUInt8=r.writeUInt8;e.writeUIntLE=r.writeUIntLE;e.writeUIntBE=r.writeUIntBE;e.writeUInt16LE=r.writeUInt16LE;e.writeUInt16BE=r.writeUInt16BE;e.writeUInt32LE=r.writeUInt32LE;e.writeUInt32BE=r.writeUInt32BE;e.writeIntLE=r.writeIntLE;e.writeIntBE=r.writeIntBE;e.writeInt8=r.writeInt8;e.writeInt16LE=r.writeInt16LE;e.writeInt16BE=r.writeInt16BE;e.writeInt32LE=r.writeInt32LE;e.writeInt32BE=r.writeInt32BE;e.writeFloatLE=r.writeFloatLE;e.writeFloatBE=r.writeFloatBE;e.writeDoubleLE=r.writeDoubleLE;e.writeDoubleBE=r.writeDoubleBE;e.fill=r.fill;e.inspect=r.inspect;e.toArrayBuffer=r.toArrayBuffer;return e}

Invalid squeezing for files without semicolon

This code (extracted from CodeMirror) is broken after applying jsqueeze on it:

    out.push(text)
    ++n

It is minified as

n.push(o)++r

while it must be

n.push(o);++r

you cannot remove the newline before an increment/decrement operator without inserting the semicolon explicitly.

TypeError: i.a$ is undefined

Input

(function($ , undefined) {
    $.fn.ace_wizard = function(options) {

        this.each(function() {
            var $this = $(this);
            $this.wizard();

            var buttons = $this.siblings(".wizard-actions").eq(0);
            var $wizard = $this.data("wizard");
            $wizard.$prevBtn.remove();
            $wizard.$nextBtn.remove();

            $wizard.$prevBtn = buttons.find(".btn-prev").eq(0).on(ace.click_event,  function(){
                $wizard.previous();
            }).attr("disabled", "disabled");
            $wizard.$nextBtn = buttons.find(".btn-next").eq(0).on(ace.click_event,  function(){
                $wizard.next();
            }).removeAttr("disabled");
            $wizard.nextText = $wizard.$nextBtn.text();

            var step = options && ((options.selectedItem && options.selectedItem.step) || options.step);
            if(step) {
                $wizard.currentStep = step;
                $wizard.setState();
            }
        });

        return this;
    }

})(window.jQuery);

Expected output

(function(e,t){e.fn.ace_wizard=function(t){this.each(function(){var i=e(this); i.wizard(); var a=i.siblings('.wizard-actions').eq(0),n=i.data('wizard'); n.t$.remove(); n.e$.remove(); n.t$=a.find('.btn-prev').eq(0).on(ace.click_event,function(){n.previous()}).attr('disabled','disabled'); n.e$=a.find('.btn-next').eq(0).on(ace.click_event,function(){n.next()}).removeAttr('disabled'); n.nextText=n.e$.text(); var r=t&&((t.selectedItem&&t.selectedItem.step)||t.step); if(r){n.currentStep=r; n.setState()}}); return this}})(window.jQuery);

Actual output

;function(e){e.fn.ace_wizard=function(t){return this.each(function(){var a=e(this);a.wizard();var i=a.siblings(".wizard-actions").eq(0),n=a.data("wizard");n.$prevBtn.remove(),n.$nextBtn.remove(),n.$prevBtn=i.find(".btn-prev").eq(0).on(ace.click_event,function(){n.previous()}).attr("disabled","disabled"),n.$nextBtn=i.find(".btn-next").eq(0).on(ace.click_event,function(){n.next()}).removeAttr("disabled"),n.nextText=n.$nextBtn.text();var s=t&&(t.selectedItem&&t.selectedItem.step||t.step);s&&(n.currentStep=s,n.setState())}),this}}(window.jQuery);

$singleLine does not create a single line

Nice script, very useful ;)

But it seems to make both consistent and "random" line breaks, even though I have $singleLine set to TRUE.
Cutting string sentences too

Like this:
alert("this is some text, and suddenly it
has a line break, but it didn't in the original javascript");

EDIT: this seems to be caused by strange editor/browser wordwrap.
But that can't be the only reason?

Fails to buil bootstrap-select.js

var args = arguments;
// The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
// to get lost/corrupted in android 2.3 and IE9 #715 #775
var _option = option,
_event = event;
[].shift.apply(args);

var value;
var chain = this.each(function () {

gets compiled to

var o=arguments,s=n,a=i;[].shift.apply(o),value,chain=this.each(function(){

but should be compiled to

var o=arguments,s=n,a=i;[].shift.apply(o);var value,chain=this.each(function(){

Broken minification in if else stanza

[ Sorry in advance for my pour JavaScript knowledge.]

Hi,

The following stanza from ace.js seems to be broken after being minified:

if ("aaa".split(/a/).length == 0)
    this.$split = function(text) {
        return text.replace(/\r\n|\r/g, "\n").split("\n");
    }
else
    this.$split = function(text) {
        return text.split(/\r\n|\r|\n/);
    };

Becomes:

if("aaa".split(/a/).length==0)this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}else this.$split=function(e){return e.split(/\r\n|\r|\n/)};

And causes the browser to choke on the minified JavaScript file.

FWIW, the following (fixed?) code provides a working minified JavaScript file:

if ("aaa".split(/a/).length == 0) {
    this.$split = function(text) {
        return text.replace(/\r\n|\r/g, "\n").split("\n");
    }
} else {
    this.$split = function(text) {
        return text.split(/\r\n|\r|\n/);
    };
}

@AdamWill, I used your fix (thanks BTW) to test OC8 with JSqueeze and ran into this issue (making the whole webui unusable, since all the JavaScript is concatenated in one file), did you find another workaround, or were you simply not affected by this issue?

Javascript and PHP mixed

First, sorry for my english.
I usually have Javascript mixed with PHP code, there any way to compress javascript code but not modify the code included between ""

Regards!
Manuel Soler.

"SyntaxError: missing } after property list" on minified ownCloud core/js/js.js

I'm working on proposing ownCloud move from mrclay/minify JSMin to JSqueeze (for licensing, maintenance, and performance reasons), but now I actually managed to get an OC 8 install up and asset pipelining enabled and stuck in my test patch to switch, I find JSqueeze seems to produce broken code when minifying ownCloud's core JS.

The file in question is (I think) https://github.com/owncloud/core/blob/01374ab6b54091a8ade4a48f8a67d42c928502e8/core/js/js.js (I'm working with that exact git commit at present). The minified version is https://www.happyassassin.net/temp/ocjs-minified.txt . When I load any ownCloud page with the JSqueeze-minified JS, it fails to work properly at all (lots of layout issues, no menus working etc) and the Firefox debugger shows:

SyntaxError: missing } after property list 5fd4952a40df28b50e6d50759345648a.js:61

ocjs-minified.txt is that line 61 from the big minified file.

I don't see the same issue with the source javascript, or with the same files minified by JSMin or JShrink.

Note, I'm invoking JSqueezeFilter like this:

            $jsqueeze = new JSqueezeFilter();
            $jsqueeze->setSpecialVarRx(false);
            return new FileAsset($root . '/' . $file, array(
                $jsqueeze
            ), $root, $file);

to try and disable the 'special' variable renaming feature, as I saw from other reports it seems to cause issues. If I drop the $jsqueeze->setSpecialVarRx(false); line the error actually goes away (and the JS gets a bit smaller), but the JS still fails to load properly.

Incompatible with AngularJS

Hi,

Using JSqueeze on ownCloud, it fails to minify correctly the JavaScript file provided by the Notes application with the following error:

Error: [$injector:modulerr] Failed to instantiate module Notes due to:
[$injector:unpr] Unknown provider: t
http://errors.angularjs.org/1.4.0-build.3841+sha.ef894c8/$injector/unpr?p0=t
p/<@http://localhost/owncloud/assets/72773572308bad612ffce802e84db88d.js:104:418
be/p.$injector<@http://localhost/owncloud/assets/72773572308bad612ffce802e84db88d.js:104:24811
[ … more lines … ]
...="+encodeURIComponent(qt(n[r]))};return new t(i)}};var Xi=/^\/(.+)\/([a-z]*)$/,e...
-------------------------------------------^

(Firebug points the 418th character of the 104th line)

The unminified counterparts it comes from is:

for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
    encodeURIComponent(toDebugString(templateArgs[i]));
}

return new ErrorConstructor(message);

I don’t believe the actual failure comes from here anyway: it’s just the error handling mechanism, as are the first hops (104:24811, 104:26521, etc.) pointed from the full debug message.

It may be related to the loading of angular.module (I really don’t understand much about JavaScript, sorry) as initiated by config/app.js and the way JSqueze shrinks this call and the actual AngularJS handling.

The three files corresponding to the three minified lines (104 to 106) are:

(Replacing those three lines by the content of those three files makes the application usable again.)

Please note that I’ve also reproduced the issue with two other versions (1.2.28 and 1.3.13) of AngularJS. I’d be happy if you could help finding a workaround if the issue is tough to fix. I’d also be happy to provide a more actionable bug report if you point me in the right direction (I have no idea how to properly debug such issue right now).

Fix #15

dc3c407
after:
else if(a.iPage<=d){l=1;n=s}
else if(a.iPage>=(a.iTotalPages-d)){l=a.iTotalPages-s+1;n=a.iTotalPages}
always comes a new line, why?

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.