How to make a class-based web component side-effec

2019-06-03 20:35发布

问题:

I have a set of spec v1 web components which I'm using webpack 4 to bundle (and babel-loader to transpile).

The components all look similar to this:

export class CompDiv extends HTMLDivElement {
  constructor(...args) {
    const self = super(...args);
    self.property = null;
    return self;
  }
  connectedCallback() {
    console.log('connected CompDiv');
  }
}

customElements.define('comp-div', CompDiv, { extends: 'div' });

Now to be able to create custom packages from these components using selective, named imports I need to mark these files as side-effect-free.

The component registration, though, takes place in the module itself:

customElements.define('comp-div', CompDiv, { extends: 'div' });

As far as I understand, that is a sideeffect.

Now I have an index.js that basically looks like this:

export { CompDiv } from './components/comp-div/comp-div';
...
export { CompBtn } from './components/comp-btn/comp-btn';

My webpack entry point looks like this:

import 'document-register-element';
import 'babel-polyfill';
import { CompDiv } from './index';

Now when I do this, CompBtn (and all other exports in index.js) ends up being part of the bundle even though it's not imported in my webpack entry point.

What would be the recommended way of allowing for treeshaking in webpack with these web components?