Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSSStyleSheet in custom elements / web-components #3583

Closed
dy opened this issue Jan 7, 2024 · 2 comments
Closed

CSSStyleSheet in custom elements / web-components #3583

dy opened this issue Jan 7, 2024 · 2 comments

Comments

@dy
Copy link

dy commented Jan 7, 2024

I am building web-component, and it seems the modern practice for including CSS is shadow.adoptStyleSheets.

Since it's not completely clear from the docs (there's 2-3 ways to load css?) - do I understand it right that I have to make text loader for css files --loader:.css=text and import it as follows:

import styles from './styles.css'
import tpl from './template.html'

class MyComponent extends HTMLElement {
  constructor() {
    super()
    
    this.attachShadow({ mode: 'open' });
    this.shadow.innerHTML = tpl;
    
    const sheet = new CSSStyleSheet();
    sheet.replaceSync(styles);
    this.shadow.adoptedStyleSheets = [sheet];
  }
}

I guess that might have issues with files included via url() in style.css, like fonts, eg. pointing to npm deps.

@evanw or anyone - would you be able to clarify what would be a good practice that case?

Thanks!

@dy dy changed the title CSSStyleSheet CSSStyleSheet in custom elements / web-components Jan 7, 2024
@evanw
Copy link
Owner

evanw commented Jan 7, 2024

There is no built-in support for doing this. Caveat: I don't use web components myself and am not the right person to ask for best practices here.

Using --loader:.css=text would certainly work, but like you said you might need to do certain things for url(). AFAIK people doing this workflow are trying to emulate the Chrome-only CSS module script feature except that the people who designed that feature punted on what @import is supposed to mean in that case, so there might not be a best practice for pointing to npm deps at the moment. Issue #3384 sort of tracks esbuild potentially implementing something like this feature in the future.

You could also consider making an on-load plugin that intercepts .css files and bundles them, returning the bundle to esbuild with loader: "text".

@dy
Copy link
Author

dy commented Jan 7, 2024

Thank you, makes sense. Maybe additional loader type? Looking forward for any implementation.
Since it will be resolved once #3384 is resolved, I will close it.

@dy dy closed this as completed Jan 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants