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?
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);
};
};