1 year ago

#365198

test-img

user3183717

How can I use SCSS in Web Components?

I'm using lit.dev to try to set up some Web Components.

However, I also want to use Bootstrap as a jumping off point for my styles, and take advantage of the themeing, variables, and mixins they provide.

I'm able to define a simple web component using Lit without much fuss, but I'm having trouble incorporating my .scss styles.

I was able to use the syntax !!loader-name!loader-name!./myFile.scss in my JavaScript import to get it to work, but this seems hacky. I'm also not sure what this syntax is called or what it is doing, if anyone can help clarify that.

My code:

// myComponent.ts

import {LitElement, css, html, unsafeCSS} from 'lit';
import {customElement, property} from 'lit/decorators.js';

import 'bootstrap'
import style from '!!css-loader!sass-loader!./myComponent.scss';
    
@customElement('my-component')
export class NavItem extends LitElement {

    static styles = css`${ unsafeCSS( style ) }`;

    render() {
        `
        return html`<p>Some Content</p>`
    }
}

// myComponent.scss

@use "../../assets/styles/style";

// Custom SCSS Code below...

// assets/styles/style.scss

@import "~bootstrap/scss/bootstrap";

I'm using Storybook, here is my webpack config in main.js:

module.exports = {
  "stories": [
    "../stories/**/*.stories.mdx",
    "../stories/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    {
      name: '@storybook/preset-scss',
      options: {
        cssLoaderOptions: {
          modules      : {
            mode: 'local'
          },
          importLoaders: 2
        },
      },
    },
    "storybook-color-picker",
    ['@babel/plugin-proposal-decorators', { decoratorsBeforeExport: true }],
  ],
  babel: async (options) => {
    Object.assign(options.plugins.find((plugin) => plugin[0].includes('plugin-proposal-decorators'))[1], {
      decoratorsBeforeExport: true,
      legacy: false
    })
    return options;
  },
  "framework": "@storybook/web-components",
  "staticDirs": ['../stories/assets']
}

Everything renders correctly, but I'm not really sure what is happening on the webpack side of things. I think what is happening is that webpack is converting my SCSS file into a string, and I am able to read that string with unsafeCSS()

My question is: Is there a better way for me to consume SCSS in Lit components?

webpack

sass

web-component

storybook

lit

0 Answers

Your Answer

Accepted video resources