thepassle / generic-components

A collection of generic web components with a focus on accessibility, and ease of use
https://genericcomponents.netlify.app/
MIT License
558 stars 29 forks source link

Add side-effect property to package.json #47

Closed danny-andrews closed 2 years ago

danny-andrews commented 3 years ago

This allows tree-shaking to work properly with bundlers like webpack and rollup.

Previously, you had to import components directly in order to prevent bloating your bundle:

import { GenericSwitch } from "@generic-components/components/generic-switch/GenericSwitch.js";

customElements.define("generic-switch", GenericSwitch);

This is verbose and non-robust, since it requires knowledge of the package's directory structure. Instead, we'd like to do this:

import { GenericSwitch } from "@generic-components/components";

customElements.define("generic-switch", GenericSwitch);

Unfortunately, the second variation includes extraneous code.

First variation: 3.5k. Second variation: 13.7k.

After adding "sideEffects" = false to package.json, the second variation results in the same bundle size as the first: 3.5k.

tbh, I'm surprised the "sideEffects" property is required to get tree-shaking to work. I thought that rollup could tree-shake any packages marked with "type": "module" and containing a "module" property pointing to a file exporting es6 modules. But, maybe there's something messing up its static analysis.

FYI: I understand the root imports (e.g. "./switch.js") contain side-effects in the form of customElements.define, but AFAIK the "sideEffects" property only applies to the modules exported from the "main" or "module" properties ("./index.js" in our case) which has no side-effects.

thepassle commented 2 years ago

Thanks for the contribution!