Search code examples
javascriptgruntjsuglifyjs

UglifyJS compression


I'm trying to get a simple example of UglifyJS (v2.3.6) to work with the compression.

Specifically, the "unused" option, where variables and functions are stripped if never used.

Here is my attempt on the command line:

echo "function x() { return 1; }; function y() { return 2; }; y();" | uglifyjs -c hoist_funs=true,hoist_vars=true,unused=true

As you can see, function "x" is never used.

Yet it is not being stripped from the result:

function x(){return 1}function y(){return 2}y();

Can anyone see what I am doing wrong?


Solution

  • In you example the functions x and y are global functions and may be used by other scripts:

    function x() {
      return 1;
    };
    function y() {
      return 2;
    };
    y();
    

    However you can define the scope by using a closure:

    (function(){
      function x() {
        return 1;
      };
      function y() {
        return 2;
      };
      y();
    })();
    

    Now x isn't used in it's scope and it may be removed without any concerns.