[英]How to add a SCSS stylesheet to a Lit web component?
I'm building a web component using lit.dev .我正在使用lit.dev构建 web 组件。 For my component, I want to import an SCSS stylesheet and use it the following way:
对于我的组件,我想导入一个 SCSS 样式表并按以下方式使用它:
// 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.我正在使用 Webpack
5.51.1
和 TS 设置这个项目。
Here's my webpack.config.js
:这是我的
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).我需要 SASS 因为我从第三方库 (Bootstrap) 导入了很多 mixins 和变量。 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.根据文档,使用外部样式表的唯一方法是通过
<link>
标签嵌入它,他们不推荐这样做。 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).但是,由于我使用的是捆绑程序,我想知道是否有任何可用的解决方法(可能是这种情况,但我是 Webpack 新手)。 Thanks!
谢谢!
update your style loader in webpack.config.js with: ' lit-scss-loader '在 webpack.config.js 中更新您的样式加载器:' 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:不要忘记安装 package 开发依赖:
npm i -D lit-scss-loader
You need to use the unsafeCSS
function to pass a string:您需要使用
unsafeCSS
function 来传递字符串:
static get styles() {
return css`${unsafeCSS(styles)}`;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.