Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[labs/ssr] expose minimal CSSStyleSheet class in SSR DOM ShimΒ #4862

@thescientist13

Description

@thescientist13

Should this be an RFC?

  • This is not a substantial change

Which package is this a feature request for?

SSR (@lit-labs/ssr)

Description

Coming out of discussions in #2631 (comment) and from the recent Lit engineering call, the topic of splitting the scope off for just providing a DOM Shim for CSSStyleSheet (distinct from handling how to actually load a CSS file in a non-browser runtime) was proposed. This would allow for the usage of CSS Module Scripts with custom elements when server-rendering.

You can see the current behavior in this reproduction repo

/* greeting.css */
p { 
  color: blue;
}
// greeting.js
import { html, css, LitElement } from 'lit';
import sheet from './greeting.css' with { type: 'css' }

export class SimpleGreeting extends LitElement {
  static styles = [ sheet ];

  // ...
}

customElements.define('simple-greeting', SimpleGreeting);

And the output from running the build script

SSR Stylesheet detected...
file:///Users/owenbuckley/Workspace/github/lit-ssr-css-modules/components/greeting/greeting.css:2
        const sheet = new CSSStyleSheet();sheet.replaceSync(`p { 
                      ^

ReferenceError: CSSStyleSheet is not defined
    at file:///Users/owenbuckley/Workspace/github/lit-ssr-css-modules/components/greeting/greeting.css:2:23
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at async file:///Users/owenbuckley/Workspace/github/lit-ssr-css-modules/register.js:5:1

The proposal for a DOM Shim itself would effectively be to stub out no-ops for the main methods of CSSStyleSheet, so as to at least not fail in an SSR context. (more work to improve their capabilities could be made over time if so desired)

class CSSStyleSheet {
  insertRule() { }
  deleteRule() { }
  replace() { }
  replaceSync() { }
}

Alternatives and Workarounds

I thought I could just shim this in from first party code or at least try and patch it through _node_modules, but it still produced the same error, so I assume it has something to do with how Lit+SSR is registering / shielding globals?

class CSSStyleSheet {
  insertRule() { }
  deleteRule() { }
  replace() { }
  replaceSync() { }
}

globalThis.CSSStyleSheet = globalThis.CSSStyleSheet ?? CSSStyleSheet;

Interestingly, I saw that CSSStyleSheet was defined in the DOM Shim, yet we still get CSSStyleSheet is undefined? πŸ€”

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    βœ… Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions