Is there a tool to remove unused methods in javascript?

Viewed 33746

I've got a collection of javascript files from a 3rd party, and I'd like to remove all the unused methods to get size down to a more reasonable level.

Does anyone know of a tool that does this for Javascript? At the very least give a list of unused/used methods, so I could do the manually trimming? This would be in addition to running something like the YUI Javascript compressor tool...

Otherwise my thought is to write a perl script to attempt to help me do this.

7 Answers

No. Because you can "use" methods in insanely dynamic ways like this.

obj[prompt("Gimme a method name.")]();

Unless the library author kept track of dependencies and provided a way to download the minimal code [e.g. MooTools Core download], it will be hard to to identify 'unused' functions.

The problem is that JS is a dynamic language and there are several ways to call a function.

E.g. you may have a method like

function test() 
{
   //
}

You can call it like

   test();

   var i = 10;
   var hello = i > 1 ? 'test' : 'xyz';

   window[hello]();

I know this is an old question by UglifyJS2 supports removing unused code which may be what you are looking for.

Also worth noting that eslint supports an option called no-unused-vars which actually does some basic handling of detecting if functions are being used or not. It definitely detects it if you make the function anonymous and store it as a variable (but just be aware that as a variable the function declaration doesn't get hoisted immediately)

In the context of detecting unused functions, while extreme, you can consider breaking up a majority of your functions into separate modules because there are packages and tools to help detect unused modules. There is a little segment of sindreshorus's thoughts on tiny modules which might be relevant to that philosophy but that may be extreme for your use case.

Related