FredKSchott / snowpack

ESM-powered frontend build tool. Instant, lightweight, unbundled development. ✌️
https://www.snowpack.dev
MIT License
19.48k stars 922 forks source link

💡 RFC: Allow importing CSS/HTML/JSON in JS resulting in the import becoming part of the JS module/bundle #3544

Open franktopel opened 3 years ago

franktopel commented 3 years ago

Motivation

Until we get CSS Module Scripts, when developing webcomponents with snowpack, authors face the problem how to integrate CSS into their components' shadow trees. Neither of the two options of using CSS in snowpack is any helpful here because both (CSS and CSS Modules) result in being added to a bundle that is meant to be used for document and obviously unavailable in any shadow root.

With webpack, using either raw-loader or style-loader authors have the option to use constructed stylesheets like this:

// import styles into a Javascript variable, at build-time becomes part of the JS
// I could also author the styles right here, but I want syntax support so the CSS
// should be authored in an external file
import styles from './foo-bar.css';

// create a constructed stylesheet using the imported CSS
const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(styles);

class FooBar extends HTMLElement {
  static get styleSheet() {
    return styleSheet;
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.adoptedStyleSheets = [...FooBar.styleSheet];
  }
}

customElements.define('foo-bar', FooBar);

Since the main selling point of snowpack over webpack is the much faster module based HMR for development, using webpack's way with raw-loader or style-loader would just mean going back to webpack, also for the development server.

I hope I'm just missing that this is already supported; if not and there are no plans to incorporate this, snowpack sadly will not be applicable for vanilla webcomponents development.

Proposed solution

Implement importing CSS in JS in a way that results in the CSS becoming part of the JS module/bundle.

Detailed design

I am not a snowpack implementer, so I have no clue as of what the detailed design would have to look like.

Open questions

Help make it happen!

franktopel commented 3 years ago

I've broadened the issue because all three (CSS, HTML, JSON) have the same issues with regard to maintenance and developer experience. The CSS part to me though is by far the most important one.