-1

I have the following code in a JS file

(() => {
    const Abc = (ab) => {
        this.ab = ab;
        this.k = () => {
            console.log(this.ab);
        };
    };
    window.MySpace = window.MySpace || {};
    window.MySpace.abc = new Abc('some var');
})();

I'm using webpack 5 as my bundler. In another file that loads after this constructor, when I tried using window.Myspace.abc.k, it threw an error. With a little investigation, I'm able to understand that the output file does not have the k, as a result of TreeShaking mechanism.

How do I tell webpack to exclude this constructor/method during treeshaking?

Green Wizard
  • 3,507
  • 4
  • 18
  • 29
  • 3
    You shouldn’t be able to use `new` on an arrow function like this in the first place…!? – deceze Jun 13 '21 at 13:10

1 Answers1

2
window.MySpace.abc = new Abc('some var');

Abc is an arrow function. Arrow functions cannot be used as a constructor, so this line of code is throwing an exception, and thus nothing gets assigned to window.MySpace.abc.

To fix this, use a regular function:

function Abc(ab) {
  this.ab = ab;
  this.k = () => {
    console.log(this.ab);
  };
};
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98