简体   繁体   中英

How to add a SCSS stylesheet to a Lit web component?

I'm building a web component using lit.dev . For my component, I want to import an SCSS stylesheet and use it the following way:

// example-component/example-component.ts
import { LitElement, HTML, css } from 'lit';
import { customElement } from 'lit/decorators.js';

import styles from './example-component.scss';

@customElement('example-component')
class ExampleComponent extends LitElement {
  static styles = styles;
  // or static styles = css`styles`;
  // or static styles = css(styles);

  render() {
    return html`
      <div class="example-component">
        <h1>Yaay! Example component.</h1>
      </div>
    `;
  }
}

export default ExampleComponent;

I'm setting up this project using Webpack 5.51.1 and TS.

Here's my webpack.config.js :

const path = require('path');
const Copy = require('copy-webpack-plugin');
const WebpackHtml = require('html-webpack-plugin');

module.exports = {
  entry: {
    'example-component': './src/example-component/example-component.ts',
  },
  mode: 'development',
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(scss|css)$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
    ],
  },
  plugins: [
    new Copy({
      patterns: [
        { from: 'manifest.json', }
      ]
    }),
    new WebpackHtml({
      filename: 'popup.html',
      chunks: './src/popup/popup.ts',
    }),
  ],
  resolve: {
    extensions: ['.ts', '.js', '.css', '.scss'],
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  }
};

I need SASS cause I'm importing a lot of mixins and variables from a third-party library (Bootstrap). According to the docs , the only way to use an external stylesheet is to embed it through a <link> tag, which they don't recommend. However, since I'm using a bundler, I was wondering if there are any workarounds available (this might be the case but I'm a Webpack newbie). Thanks!

update your style loader in webpack.config.js with: ' lit-scss-loader '

It should look like this:

`

            test: /\.(scss|css)$/,

            use: [{
                loader: 'lit-scss-loader',
                options: {
                    // defaultSkip: true,
                    minify: true
                },
            }, 'extract-loader', 'css-loader', 'sass-loader'],

Don't forget to install package dev dependancy:

npm i -D lit-scss-loader

You need to use the unsafeCSS function to pass a string:

static get styles() {
    return css`${unsafeCSS(styles)}`;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM