closure-compiler icon indicating copy to clipboard operation
closure-compiler copied to clipboard

Bug: static class members defined via an IIFE cause the class to not be removed

Open bradzacher opened this issue 10 months ago • 1 comments

Input

function getFoo() {
  class Foo {
  }
  (() => {
    Foo.x = 1;
  })();
  return Foo;
}
const Foo1 = getFoo();

class Bar {
  constructor(num) {
    this.num = num;
  }

  n() {
    console.log(this.num);
  }

  neverCalled() {
    console.log(Foo1);
  }
}

new Bar(5).n();

Expected output

function b() {
  this.g = 5;
}
b.prototype.n = function() {
  console.log(this.g);
};
(new b()).n();

Actual output

(function() {
  function a() {
  }
  a.x = 1;
  return a;
})();
function b() {
  this.g = 5;
}
b.prototype.n = function() {
  console.log(this.g);
};
(new b()).n();

closure compiler playground

From the looks of it, CC's side-effect detection doesn't correctly understand the IIFE and CC decides the enclosing scope is impure. This in turn means that CC won't remove the unused code paths.

We ran into this because this is the code that swc generates for static class members. I'm trying to migrate our codebase from tsc to swc for transpilation and we noticed a bundle size increase. A lot of investigation later we eventually narrowed it down to this problem.

cc @WearyMonkey

bradzacher avatar Sep 07 '23 05:09 bradzacher