Skip to content

Some questions about tree-shaking #697

@Ercilan

Description

@Ercilan

First, the main issue is that all the top-level code such as addEventListener and window.$hsThemeSwitchCollection should be moved inside the block if (typeof window !== "undefined") { ... }. Otherwise, the conditional branches below are meaningless.

window.addEventListener("load", () => {
HSThemeSwitch.autoInit();
// Uncomment for debug
// console.log('Theme switch collection:', window.$hsThemeSwitchCollection);
});
if (window.$hsThemeSwitchCollection) {
window.addEventListener(
"on-hs-appearance-change",
(evt: Event & { detail: string }) => {
window.$hsThemeSwitchCollection.forEach((el) => {
(el.element.el as HTMLInputElement).checked = evt.detail === "dark";
});
},
);
}
if (typeof window !== "undefined") {
window.HSThemeSwitch = HSThemeSwitch;
}


Next is the tree-shaking problem. After fixing the first issue, it becomes possible in Nuxt (SSR) to import only the required components, for example: import { HSOverlay } from "preline"; instead of import "preline/dist"; which imports the pre-bundled file that includes all components.

(Under normal circumstances, source code should be not imported in our project directly?)

I tested this locally: by importing only the required components, my final bundle size was reduced by over 100KB (for me).

Image

However, in the generated code, all components are still imported (this might still need to be addressed), though some code is gone—perhaps it was optimized? The component I need is performing normally in testing.

It would be great if you could provide an official example for on-demand imports / tree-shaking. Importing just 7 components adds ~350KB of JS, which is too large.

I know there are separate packages, but as far as I understand, preline’s JS library is mainly plugins and standalone classes, which should be tree-shakable?
I hope to receive some answers and suggestions from you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions