find dead JavaScript code?

后端 未结 8 863
醉酒成梦
醉酒成梦 2020-12-05 05:51

We are refactoring a legacy web app and as a result are \"killing\" quite a lot of JavaScript code but we\'re afraid of deleting what we think is dead code due to not being

相关标签:
8条回答
  • 2020-12-05 06:35

    You can use deadfile library: https://m-izadmehr.github.io/deadfile/

    It can simply find unused files, in any JS project.

    Without any config, it supports ES6, JSX, and Vue files:

    0 讨论(0)
  • 2020-12-05 06:38

    There's grep. Use it to find function calls. Suppose you have a method called dostuff(). Use grep -r "dostuff()" * --color on your project's root directory. Unless you find anything other than the definition, you can safely erase it.

    ack is also a notable alternative to grep.

    0 讨论(0)
  • 2020-12-05 06:45

    Chrome has come up with new feature which lets developer see the code coverage, ie., which lines of codes were executed.

    This certainly is not a one stop solution, but can extend a helping hand to developers to get code insights.

    Check this link for details

    Rolled as apart of Chrome 59 release

    0 讨论(0)
  • 2020-12-05 06:48

    Without looking for anything too complex:

    • JSLint (not really a static analyzer, but if you give it your concatenated development code, you'll see what methods are never called, at least in obvious scoping contexts)
    • Google Closure Compiler
    • Google Closure Linter
    0 讨论(0)
  • 2020-12-05 06:48

    If you want to automate this I'd take a look at https://github.com/joelgriffith/navalia, which exposes an automated API to do just that:

    const { Chrome } = require('navalia');
    const chrome = new Chrome();
    
    chrome.goto('http://joelgriffith.net/', { coverage: true })
      .then(() => chrome.coverage('http://joelgriffith.net/main.bundle.js'))
      .then((stats) => console.log(stats)) // Prints { total: 45913, unused: 5572, 
      percentUnused: 0.12135996340905626 }
      .then(() => chrome.done());
    

    More here: https://joelgriffith.github.io/navalia/Chrome/coverage/

    0 讨论(0)
  • 2020-12-05 06:51

    You could use code optimizers as Google Closure Compiler, however it's often used for minimizing code.

    function hello(name) {
    alert('Hello, ' + name);
    }
    
    function test(){
    alert('hi');
    }
    
    hello('New user');
    

    Will result in

    alert("Hello, New user");
    

    For example.

    Another thing you could do is to use Chrome's Developer Tools (or Firebug) to see all function calls. Under Profiles you can see which functions are being called over time and which are not.

    DT Profiles

    0 讨论(0)
提交回复
热议问题