-
Notifications
You must be signed in to change notification settings - Fork 378
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
Cascading Style Sheet module scripts #759
Comments
To clarify that this would be useful for non-Shadow DOM use cases, especially for those who aren't familiar with the Constructible StyleSheet Objects proposal, here's how you would implement the side-effectful style of loading common today: import styles from './styles.css';
document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles]; Modules that currently use CSS loaders that write to global styles would just have to add the Loaders that modify selectors could still work at build time, or runtime with a call to mutate the stylesheet: import styles from './styles.css';
import 'styleScoper' from 'x-style-scoper';
// extract original class names, and rewrite class names in the StyleSheet
const classNames = styleScoper(styles);
document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles];
// Use the rewritten class names
`<div class="${classNames.exampleClass}"></div>` edit: updated to use current Constructible Stylesheets API |
cc @tabatkins |
So the idea is just that the browser would recognize |
@tabatkins yep. Though it'd be triggered off the mime-type, as I think WASM modules are proposed to do. (edit: uh, yes, you already said I think this should be pretty simple. One question I didn't list is when to resolve the CSS Module in the presence of |
I like this as a feature, but would mean that files containing custom elements must have a common structure in order to be reused (the path to |
I don't quite understand this. The import specifier is a URL like any other import, and can be a relative or absolute URL to a file anywhere a JS module could be. There won't need to be any additional conventions that I can see. |
Right, but two different apps using the same component will need similar structures or to change the component file's code for their app. If I publish a component through NPM and it's consumed by one app that way and another pulls from GitHub, but has different locations for scripts/CSS, there might be issues. Ultimately it's not that big of a deal, but something that should be considered. |
I don't think there's anything to consider in this proposal. Component distribution is another issue entirely, one that might be solved by webpackage or something else. For the time being we can only distribute components as multiple files. In which case if someone hands you a JS script and a CSS module as siblings you should not be under the impression that you can then split those up in different locations on your server. |
This could probably be implemented as a JS library if we had a more generic way to hook in to |
@AshleyScirra I think that idea is interesting but probably has a lot more discussion needed before it's ready. I see a number of problems with it as is. For example, what exactly is the Type? In some cases it seems to be an existing global object and others something new. Is SelectorAll going to be a new global? Would it have a purpose outside of this use case? And what happens if the global doesn't exist? If do Not trying to downplay your work, it's an interesting approach and I like the simplicity of using a symbol. Having observed what happened with previous attempts at defining loader hooks I would really hope browser vendors don't pass on a chance at implementing a simple and practical solution such as the CSS module idea from this issue in favor of waiting on something more generic, but much more complex. |
It's any object that has a |
@AshleyScirra I think we should collect discussion of a more generic "import as" mechanism in it's own issue. I like the idea, but I think there's a place for extensible loading and several built-in module types other than just JavaScript. Browsers natively understand (including prescanning and parsing) JS, HTML and CSS. It makes sense for the module system to understand them as well. |
Regarding the It doesn't belong to this particular discussion, but I think the question arises naturally when you're discussing about a way to import other things into JS. We (the webpack team) already had a long discussion when we tried to streamline this with browserify. It's kind of limiting if the platform defines how these assets are imported. In the long run, I'd really appreciate if there was a way to import assets into JS while allowing the importer to define the how. Kudos to @AshleyScirra 👏 Regarding this proposal: However, it still makes sense to define a sensible default behavior for common things like importing CSS. It also helps us to get a better understanding of the domain and maybe also helps to speed up the development of these generic import proposals. I really like @justinfagnani 's proposal because it doesn't introduce new concepts. It looks very consistent with other parts of the web components API, like the Speaking as an application developer, it would be very useful to have a way to reference CSS class names from JavaScript. This makes it easier for bundlers and other tools to statically analyze the usage of class names. It allows them to remove unused class names. I think this makes current CSS-in-JS solutions like styled-components and the CSS modules project so appealing: it just plays well with existing tools because it makes it statically analyzable. It also makes things like Sass and Less obsolete as we can use JavaScript for that. There is also a different approach: Instead of standardizing CSS module imports, we could also make the CSSOM better approachable from the JS-side. The Constructable Stylesheet Objects proposal is a step in the right direction. Consider we'd allow the developer to write code like this: import uuid from "uuid";
import {regularPadding} from "../styles/paddings.js";
import {regularMargin} from "../styles/margins.js";
import {modularScale} from "../styles/typography.js";
const hamsterImage = new URL("../hamsters.jpg", import.meta.url);
export const modal = `modal-${uuid}`;
export const header = `header-${uuid}`;
export default CSSStyleSheet.parse`
.${modal} {
background-image: url(${hamsterImage});
padding: ${regularPadding};
}
.${header} {
font-size: ${modularScale(2)};
}
.${modal} > ${header}:not(:last-child) {
margin-bottom: ${regularMargin};
}
`; Inside the component, you'd do: import (LitElement, html} from "lit-element";
import styles, {modal, header} from "./styles.js";
class MyElement extends LitElement {
constructor() {
this.attachShadow({mode: open});
this.shadowRoot.moreStyleSheets.push(styles); // push() doesn't actually exist yet
}
render() {
return html`<section class="${modal}">
<h1 class="${header}">
This is a modal
</h1>
</section>`;
}
} You could also put everything into one file, leaving that decision up to the developer. With that approach, we wouldn't need to standardize this and still had all the flexibility the ecosystem needs. Tools like bundlers are already able to analyze that code. They could even remove styles that are not used anymore (also this is a more complex operation with my example). The developer could also decide to wrap the class names with a library: import className from "some-library";
export const modal = className("modal"); This allows the library to track all used class names during render. This is how other CSS-in-JS libraries enable developers to include the critical styles on server render. Of course, this approach has several caveats, but the point is that this is all solvable in userland without specification. |
One of the things to be noted about using imported stylesheets is So my question is, what should be the document and url of an imported stylesheet? |
@TakayoshiKochi it would help if you could elaborate on how you reached the single-document conclusion. If we allow reuse across shadow trees it seems reuse across documents isn't necessarily problematic either. There is some state obtained from the document I suppose (e.g., quirks, fallback encoding), but we could simply set those to no-quirks and UTF-8 for these new style sheets. |
(The URL of an imported style sheet should be the (eventual) response URL btw.) |
@annevk I think there was also a problem with which fetch groups the stylesheet will be in if it's constructed in one Document and used in another (see WICG/construct-stylesheets#15) |
Hmm yeah, it'd be nice if we had those formally defined. It seems in this case it should reuse the fetch group used by the JavaScript module. |
It does seem that |
In the case of constructed stylesheets, the For imported stylesheets, what if we do this: |
It sounds reasonable, except I'd still like to see justification for the document restriction. |
Oh, sorry - I misunderstood your previous comments. I'm actually not quite familiar with fetch groups (do you know where can I look for background reading? I tried looking for the specs but no luck...) But if the imported stylesheet can just reuse the fetch group used by the JavaScript module then that sounds fine to me to make it usable in many document trees. For constructed stylesheet case, let's continue discussion on WICG/construct-stylesheets#15. |
@rakina now it's my turn to apologize. The high-level concept is documented at https://fetch.spec.whatwg.org/#fetch-groups, but it requires integration with HTML and that isn't done. It's effectively a collection of all fetches a document/global is responsible for so they can be managed together in case the document/global goes away (e.g., a tab is closed). In Gecko this is called a "load group". I suspect Chromium has a similar concept. |
That issue is being discussed over at this thread, and changes to the import syntax like those suggestions are one of the options being considered. |
This thread seems to be getting pretty long. It's not quite clear where the proposal currently stands and what the best way to submit feedback is. E.g. is it more than a historical accident that this issue in in the webcomponents repo? Would non-webcomponents feedback be relevant here? Given the overlap with existing patterns in ecosystem code (for better or worse), it seems to me like this discussion may deserve a more prominent place. |
@jkrems I opened it here because this is where we were also discussing HTML modules. I'm not sure how others feel about potentially forking the discussion vs finding a more prominent home, but I think at this point that this issue is well-known enough and referenced from other places (explainers, spec PRs, etc) that I'd be inclined to continue the discussion here. And non-web-components related feedback is most definitely welcome - this proposal is for minimal semantics that have no real coupling with web components aside from constructible stylesheets. |
@Rich-Harris , I wonder why you did not use Was you intention to prevent such bugs in the client code by a more limited interface? Did you have other intention? Corrected code: arr = ['a'];
function resolveAfter (value, ms) {
return new Promise(f => setTimeout(() => f(value), ms));
}
async function addB() {
arr.push(await resolveAfter('b', 100));
}
async function addC() {
arr.push(await resolveAfter('c', 50));
}
addB();
addC();
// later...
console.log(arr); // ['a', 'c', 'b'] |
This change extends the JavaScript module system integration to include CSS module scripts, in addition to JavaScript module scripts. These allow web developers to load CSS into a component definition in a manner that interacts seamlessly with other module script types. Explainer document: https://github.com/w3c/webcomponents/blob/gh-pages/proposals/css-modules-v1-explainer.md Closes WICG/webcomponents#759. Part of #4321. This change includes the integration for the import assertions proposal (https://github.com/tc39/proposal-import-assertions/), thus closing #5640 and closing #5883 by superseding it.
support has landed in chrome: https://web.dev/css-module-scripts/ |
This is beautiful |
Closing as this feature is standardized and should have been closed as part of the HTML Standard change. |
This change extends the JavaScript module system integration to include CSS module scripts, in addition to JavaScript module scripts. These allow web developers to load CSS into a component definition in a manner that interacts seamlessly with other module script types. Explainer document: https://github.com/w3c/webcomponents/blob/gh-pages/proposals/css-modules-v1-explainer.md Closes WICG/webcomponents#759. Part of whatwg#4321. This change includes the integration for the import assertions proposal (https://github.com/tc39/proposal-import-assertions/), thus closing whatwg#5640 and closing whatwg#5883 by superseding it.
Brillant, well done to all! This really helps make web components much more usable in the real world. Any idea if this would be possible to polyfill? Can't find any polyfills for it. |
@mangelozzi Check out |
In addition to HTML Modules, the ability to load CSS into a component definition is an important capability that we're currently lacking. Loading CSS is probably a more important use case judging by the popularity of CSS loaders in JavaScript bundlers.
Currently, styles are usually either defined inline with HTML templating or JSX or loaded with various JS Bundler CSS Loaders. The CSS loaders often have global side-effects like appending a
<style>
tag to the document, which does not generally work well with the style scoping of Shadow DOM.I propose that we add Cascading Style Sheet module scripts to the platform, allowing CSS to be imported directly by JavaScript:
Exports
The semantics for Cascading Style Sheet module scripts can be very simple, and combined with Constructable Stylesheets allow the importer to determine how the CSS should be applied to the document.
To start with, the only export of a Cascading Style Sheet module script would be a default export of the CSSStyleSheet object. This can then simply be added to
document.styles
orshadowRoot.styles
:Additional Features
Other userland CSS module systems often have more features, like the ability to import or export symbols that are defined in the module. ie:
These features may be very useful, but they can be considered for addition to the CSSOM itself so that they're exposed on CSSStyleSheet and available to both Cascading Style Sheet module scripts and styles loaded via
<style>
and<link>
tags, or constructed from a string.Polyfilling
It's not easy to polyfill a new module type, but build-time tools can create JavaScript modules that adhere to the Cascading Style Sheet module script interface.
Can be compiled to:
edit: updated to the actually Constructible StyleSheet API.
edit: updated to refer to the feature by "Cascading Style Sheet module script"
The text was updated successfully, but these errors were encountered: