51

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 7

45

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

obj[prompt("Gimme a method name.")]();
Sign up to request clarification or add additional context in comments.

10 Comments

Yeah, the best you could do is a rough pass.
I'm going to start using this method on all my projects.
but barring the example and other user-generated/random-generated methods, couldn't you whittle down the files?
@jedierikb - No. There's no reliable way to determine exactly which code will run.
This answer makes good points for the argument about how difficult it is, but the answer is 100% wrong. For everyone saying there is no way to determine which functions are run... you need to use your imagination. Tracing has been around for a very long time, and it is more than possible. Just because something doesn't exist yet for a language doesn't mean it is impossible or won't ever be available. This answer is short and lacking a lot of potentially helpful information.
|
19

Check out JSCoverage . Generates code coverage statistics that show which lines of a program have been executed (and which have been missed).

1 Comment

Quotation from JSCoverage webpage: Note: Any future development of the JSCoverage code base will likely occur in the new JSCover (tntim96.github.io/JSCover) project on GitHub, which reuses a substantial amount of JSCoverage code and aims for a high degree of backward compatibility with JSCoverage. JSCoverage itself is unlikely to have any further releases.
7

I'd like to remove all the unused methods to get size down to a more reasonable level.

There are a couple of tools available:

npm install -g fixmyjs
fixmyjs <filename or folder>

A configurable module that uses JSHint (Github, docs) to flag functions that are unused and perform clean up as well.

I'm not sure that it removes undefined functions as opposed to flagging them. though it is a great tool for cleanup, it appears to lack compatibility with later versions of ECMAScript (more info below).

There is also the Google Closure Compiler which claims to remove dead JS but this is more of a build tool.

Updated

If you are using something like Babel, consider adding ESLint to your text editor, which can trigger a warning on unused methods and even variables and has a --fix CLI option for autofixing some errors and style issues.

I like ESLint because it contains multiple plugins for alternate libs (like React warnings if you're missing a prop), allowing you to catch bugs in advance. They have a solid ecosystem.

As an example: on my NodeJS projects, the config I use is based off of the Airbnb Style Guide.

1 Comment

it seems, surprisingly, that eslint can not autofix unused variables..
4

You'll have to write a perl script. Take no notice of the nay-sayers above.

Such a tool could work with libraries that are designed to only make function calls explicitly. That means no delegates or pointers to functions would be allowed, the use of which in any case only results in unreadable "spaghetti code" and is not best practice. Even if it removes some of these hidden functions you'll discover most if not all of them in testing. The ones you dont discover will be so infrequently used that they will not be worth your time fixing them. Dont obsess with perfection. People go mad doing that.

So applying this one restriction to JavaScript (and libraries) will result in incredible reductions in page size and therefore load times, not to mention readability and maintainability. This is already the case for tools that remove unused CSS such as grunt_CSS and unCSS (see http://addyosmani.com/blog/removing-unused-css/) and which report typical reductions down to one tenth the original size.

Its a win/win situation.

Its noteworthy that all interpreters must address this issue of how to manage self modifying code. For the life of me I dont understand why people want to persist with unrestrained freedom. As noted by Triptych above Javascript functions can be called in ways that are literally "insane". This insane fexibility corrupts the fundamental doctrine of separation of code and data, enables real-time code injection, and invalidates any attempt to maintain code integrity. The result is always unreadable code that is impossible to debug and the side effect to JavaScript - removing the ability to run automatic code pre-optimisation and validation - is much much worse than any possible benefit.

AND - you'd have to feel pretty insecure about your work to want to deliberately obsficate it from both your collegues and yourself. Browser clients that do work extremely well take the "less is more" approach and the best example I've seeen to date is Microsoft Office combination of Access Web Forms paired with SharePoint Access Servcies. The productivity of having a ubiquitous heavy tightly managed runtime interpreter client and its server side clone is absolutely phenomenal.

The future of JavaScript self modifying code technologies therfore is bringing them back into line to respect the...

KISS principle of code and data: Keep It Seperate, Stupid.

2 Comments

I really am sorry, but I must LOL slightly -- your good points are greatly abrogated by your refusal to acknowledge the raw potency of javascript's "insanity." There are many patterns in modern JS development that drive me nuts, but dynamism is not amongst them. The driving forces behind unmanageable spaghetti code are largely an issue of developer discipline, not an inevitability of the language itself. =)
I'm not going to "acknowledge" anything about something of which "insanity" is already acknowledged. Its insane. You cant reason with "insane". It ends further discussion.
3

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]();

1 Comment

This hello(); will throw an error that 'helo' or 'xyz' is not a function but string.
2

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.

Comments

0

Following would help:

  1. If you have fully covered test cases, running Code Coverage tool like istanbul (https://github.com/gotwarlost/istanbul) or nyc (https://github.com/istanbuljs/nyc), would give a hint of untouched functions.

  2. At least the above will help find the covered functions, that you may thought unused.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.