Remove unused javascript code based on coverage report

后端 未结 6 696
北海茫月
北海茫月 2021-02-05 07:45

There is a big javascript library (~ 40 000 lines of code) and an application which uses less than 50% of the library\'s code.

There is a test which uti

6条回答
  •  失恋的感觉
    2021-02-05 08:15

    Closure Compiler provides some quite advanced unused code clean up features. Some examples:

    Removing a dead code block

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

    Compiles to:

    alert("Hello, New user 1");
    alert("Hello, New user 2");
    

    completely stripping away the hi function and inlining hello. (live demo)

    Moving to a more complicated case

    As the code gets more complicated, it finds new ways to optimize. For example:

    let greeted = 0;
    
    function hello(name) {
      greeted += 1;
      alert('Hello, ' + name);
    }
    
    function hi(name) {
      greeted += 1;
      alert('Hi, ' + name);
    }
    
    hello('New user ' + greeted);
    hello('New user ' + greeted);
    

    Becomes:

    var a = 0;
    function b() {
      var c = "New user " + a;
      a += 1;
      alert("Hello, " + c);
    }
    b();
    b();
    

    (live demo)

    Make sure you turn on the ADVANCED_OPTIMIZATIONS compilation level to enable dead code removal.

提交回复
热议问题