Skip to content

Importing styles in lit webcomponent fails with Vite #14142

Closed

Description

@mcollovati

Description of the bug

Giving a lit based webcomponent that imports CSS with an import directive, when the element is rendered an errors occurs preventing the component to be shown.

css-tag.ts:143 Uncaught TypeError: Failed to set the 'adoptedStyleSheets' property on 'ShadowRoot': Failed to convert value to 'CSSStyleSheet'.
    at adoptStyles (css-tag.ts:143:32)
    at HelloWorldView.createRenderRoot (reactive-element.ts:1000:5)
    at HelloWorldView.createRenderRoot (lit-element.ts:139:30)
    at HelloWorldView.connectedCallback (reactive-element.ts:1019:27)
    at HelloWorldView.connectedCallback (lit-element.ts:189:11)
    at Router.__addAppearingContent (router.js:815:23)
    at router.js:498:16

The client side view is defined as following

import '@vaadin/vaadin-text-field';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import styles from './hello-world-view.css';

@customElement('hello-world-view')
export class HelloWorldView extends LitElement {
  name: string = '';

  static styles = [styles];

  render() {
    return html`
      <vaadin-text-field label="Your name" @value-changed="${this.nameChanged}"></vaadin-text-field>
    `;
  }
  nameChanged(e: CustomEvent) {
    this.name = e.detail.value;
  }
}

the css file

:host {
  display: block;
  padding: 1em;
  background-color: orange;
}

index.ts

// import Vaadin client-router to handle client-side and server-side navigation
import { Router } from '@vaadin/router';

// import Flow module to enable navigation to Vaadin server-side views
import { Flow } from '@vaadin/flow-frontend/Flow';

const { serverSideRoutes } = new Flow({
  imports: () => import('../target/frontend/generated-flow-imports')
});

const routes = [
  // for client-side, place routes below (more info https://vaadin.com/docs/v15/flow/typescript/creating-routes.html)
    {
        path: 'hello',
        component: 'hello-world-view',
        action: async () => {
            await import('./hello/hello-world-view');
        },
    },

  // for server-side, the next magic line sends all unmatched routes:
  ...serverSideRoutes // IMPORTANT: this must be the last entry in the array
];

// Vaadin router needs an outlet in the index.html page to display views
const router = new Router(document.querySelector('#outlet'));
router.setRoutes(routes);

Minimal reproducible example

  • Create new application from start.vaadin.com with Vite enabled
  • Add the the client-side view and css in frontend/hello folder
  • Create the custom index.ts in fronted directory
  • start the application with mvn
  • Open browser at http://localhost:8080/hello

Expected behavior

CSS rules are applied to the custom web component

Actual behavior

The component is not rendered and the previously reported error is visible in the console

Versions:

- Vaadin / Flow version: 23.1
- Java version: 11
- Development mode
- Project from start.vaadin.com

Activity

  1. mcollovati commented on Jul 5, 2022

    @mcollovati
    CollaboratorAuthor

    In Webpack configuration there's lit-css-loader.
    For Vite there is rollup-plugin-lit-css, but I didn't manage to make it work correctly.

  2. self-assigned this
    on Jul 27, 2022
  3. mshabarov commented on Jul 28, 2022

    @mshabarov
    Contributor

    This was a similar issue for webpack #9532.
    It was fixed by adding two extra loaders:

    {
       loader: "lit-css-loader"
    },
    {
       loader: "extract-loader"
    },
    
  4. mshabarov commented on Aug 5, 2022

    @mshabarov
    Contributor

    I've tested with flow-tests/test-custom-frontend-directory/test-themes-custom-frontend-directory module:

    1. Added defaults.put("rollup-plugin-lit-css", "3.2.1"); to the NodeUpdater.
    2. Modified vite.config.ts as follows:
    import { UserConfigFn } from 'vite';
    import { overrideVaadinConfig } from './vite.generated';
    import litcss from 'rollup-plugin-lit-css';
    
    const customConfig: UserConfigFn = (env) => ({
      // Here you can add custom Vite parameters
      // https://vitejs.dev/config/
    
        plugins: [
            {
                ...litcss()
                , enforce: 'post'
            },
        ]
    
    });
    
    export default overrideVaadinConfig(customConfig);
    
    1. Modified hello-world-view.ts to log the styles:
    //   static styles = [styles];
    
        static get styles() {
           console.log("styles = " + styles);
           return styles;
        }
    
    1. Removed bg color style from side-src/main/frontend/themes/app-theme/components/shared/background-color.css to not override the component's style.

    I've got the following

    import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from "/VAADIN/@vite/client"
    const __vite__id = "/Users/mikhail/workspace/vaadin/flow/flow-tests/test-custom-frontend-directory/test-themes-custom-frontend-directory/side-src/main/frontend/typescript/hello-world-view.css"
    const __vite__css = ":host {\n  display: block;\n  padding: 1em;\n  background-color: black;\n}\n"
    __vite__updateStyle(__vite__id, __vite__css)
    import.meta.hot.accept()
    export default __vite__css
    import.meta.hot.prune(() => __vite__removeStyle(__vite__id))
    

    With Webpack it contains :host {\n display: block;\n padding: 1em;\n background-color: black;\n}\n.
    So the LitElement styles gets unexpected content and perhaps rollup-plugin-lit-css need an extra customisation.

    This is weird, because the docs (https://www.npmjs.com/package/rollup-plugin-lit-css) describe the similar case.

  5. removed their assignment
    on Aug 5, 2022
  6. mshabarov commented on Aug 8, 2022

    @mshabarov
    Contributor

    Can also be replicated with flow-tests/test-themes.
    Besides not working injection of styles from hello-world-view.css, it has a problem of erroneously leaked styles from custom theme (image background and text field background colour).

  7. web-padawan commented on Aug 8, 2022

    @web-padawan
    Member

    One option worth trying would be to use another plugin rollup-plugin-postcss-lit (latest version is 2.0.0):

    import postcssLit from 'rollup-plugin-postcss-lit';
      // in Vite config
      plugins: [
        postcssLit()
      ]

    See https://github.com/umbopepato/rollup-plugin-postcss-lit#usage-with-vite

  8. added a commit that references this issue on Aug 9, 2022
    fccffb2
  9. vaadin-bot commented on Aug 18, 2022

    @vaadin-bot
    Collaborator

    This ticket/PR has been released with Vaadin 23.2.0.beta1 and is also targeting the upcoming stable 23.2.0 version.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions