Reputation: 5236
I have a typescript file that import a web-component. when I import my web component like below it works fine without problem:
import 'jb-input';
const elem:any = document.querySelector('#username')
but in typescript, I have to set my elem
type to web component Class type so i import its class
import {JBInputWebComponent} from 'jb-input';
const elem:JBInputWebComponent = document.querySelector('#username')
in this case, my input web component stop working and the rollup tree shake the entire script file because it think I don't use its code but the web component needs to be defined in HTML context in its own file. question is what can I do in my web component or ts file or rollup to stop tree-shaking web component file?
Upvotes: 1
Views: 1571
Reputation: 21984
Rollup will tree-shake unused code, and it does so on the Javascript, not the Typescript, meaning that if the import is only really used by Typescript and it has side-effects (like calling document.registerElement
) then you will not get the result you want. Rollup however does understand this:
import 'some_module';
To mean that the import is for side-effects and it won't shake out that code, so you can just do both in your code:
import 'some_module';
import { SomeWebComponent } from 'some_module';
const component: SomeWebComponent | null = document.querySelector('#username');
Note the | null
on the type, you do have to account that document.querySelector
and the other DOM methods may return null if they don't find the thing you want.
Upvotes: 2