Skip to content

[labs/ssr] Can not use css files #2631

Open

Description

@daKmoR

Description

I can not use css files to style my component as css import assertions error on node.

Steps to Reproduce

  1. Write this code

👉 style.css

:host {
  background: green;
}

👉 index.js

import { render } from "@lit-labs/ssr/lib/render-with-global-dom-shim.js";
import { html, LitElement, css } from 'lit';

import style from './style.css' assert { type: 'css' };

class MyElement extends LitElement {
  static styles = [style, css`
    :host {
      background: red;
    }
  `];

  render() {
    return html`
      <h2>MyElement</h2>
    `;
  }
}

customElements.define('my-element', MyElement);

const template = ({ title }) => html`
  <p>${title}</p>
  <my-element></my-element>
`;

const ssrResult = render(template({ title: "hello world" }));
let ssrString = '';

for (const s of ssrResult) {
  ssrString += s;
}

console.log(ssrString);
  1. run node index.js

Expected Results

SSR Result logged to console

Actual Results

node index.js
node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".css" for /Users/html/test-ssr/style.css
    at new NodeError (node:internal/errors:372:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:56:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:83:38)
    at defaultLoad (node:internal/modules/esm/load:21:20)
    at ESMLoader.load (node:internal/modules/esm/loader:363:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:282:22)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:301:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:260:34)
    at async ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:81:21) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v17.6.0

Browsers Affected

  • Tested in node 16 & 17

Activity

  1. justinfagnani commented on Mar 11, 2022

    @justinfagnani
    Collaborator

    Since Node doesn't support CSS modules, we'll only be able to support this with our own module loader, which does require the --experimental-vm-modules flag, or with loader hooks whenever they arrive.

    Another approach is to treat Node more like a somewhat legacy browser and bundle the app with plugins that polyfill CSS modules. We would still need to add CSSStyleSheet to our DOM shim though.

  2. daKmoR commented on Mar 11, 2022

    @daKmoR
    ContributorAuthor

    As vm-modules and loaders are both experimental I opted for loader as it was easier for me.

    Here is a lit specific loader (requires node 17.1.0+)

    import { readFile } from 'fs/promises';
    
    /**
     * @param {string} url
     * @param {{ format: string, importAssertions: { type?: 'module' | 'json' | 'css' } }} context
     * @param {Function} defaultLoad
     * @returns {Promise<{ format: string, source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array }>}
     */
    export async function load(url, context, defaultLoad) {
      const { importAssertions } = context;
      if (importAssertions.type === 'css') {
        const content = await readFile(new URL(url)).then(res => res.toString());
        return {
          format: 'module',
          source: [
            //
            "import { css } from 'lit';",
            'export default css`',
            content,
            '`;',
          ].join('\n'),
        };
      }
      return defaultLoad(url, context, defaultLoad);
    }

    you enable the loader via the command line

    node --experimental-loader ./path/to/litCssLoader.js ./ssr-server.js

    and voila SSR output with css import assertions 💪

  3. justinfagnani commented on Mar 15, 2022

    @justinfagnani
    Collaborator

    @augustjk @aomarks this is another consideration in VM modules vs workers. Seems like we can support CSS modules in either, but it will require a flag either way. I'm unsure whether you can scope the loader to a worker though so that we don't enable CSS modules for the server app.

  4. changed the title [-][SSR] Can not use css files[/-] [+][ssr] Can not use css files[/+] on Jun 10, 2022
  5. moved this to 📋 Triaged in Lit Project Boardon Jun 10, 2022
  6. changed the title [-][ssr] Can not use css files[/-] [+][labs/ssr] Can not use css files[/+] on Mar 23, 2023
  7. daKmoR commented on Mar 9, 2024

    @daKmoR
    ContributorAuthor

    little update => experimental-loaders have been "deprecated" in favour of module register (which is a release candidate currently)

    Read the official Documentation about Hooks (module registration is one hook)
    https://nodejs.org/api/module.html#customization-hooks

    simplest way to use a loader seems to have a "setup file" that registers the load and then dynamically loads your code

    import { register } from "node:module";
    import { pathToFileURL } from "node:url";
    
    register("./loader.js", pathToFileURL("./"));
    
    await import('./your-code.js');
  8. cdennington commented on Oct 29, 2024

    @cdennington

    I have added my own loader which loads in my CSS file in much the same way as @daKmoR.
    Image

    I then register it, and call that registration file with the import flag on the command line.

    Node will then start as expected.

    However when I load the UI in the browser, only some of the styles appear to be working, and I get the following console error:
    Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/css". Strict MIME type checking is enforced for module scripts per HTML spec.

    I'm assuming the browser is still seeing my CSS as CSS but being loaded as JavaScript, hence the error.

    Are you able to provide an example of your approach, and how you then load the CSS into your components?

  9. thescientist13 commented on Dec 8, 2024

    @thescientist13
    Contributor

    On the topic of specifically supporting a minimal CSSStyleSheet DOM Shim (separate from the scope of how to load non-JS files in Node), I have created an issue here for that conversation.

  10. justinfagnani commented on Nov 21, 2025

    @justinfagnani
    Collaborator

    @kyubisation do you think #4879 closed this issue?

  11. kyubisation commented on Nov 21, 2025

    @kyubisation
    Contributor

    I think so. I'm afraid I don't remember, why I only wrote "Relates to " this issue.
    From looking at the issue description, this should now be supported via --module=@lit-labs/ssr/lib/install-global-dom-shim.js or directly via --module=@lit-labs/ssr-dom-shim/register-css-hook.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions