use*_*849 5 css web-component shadow-dom bootstrap-4 lit-element
使用 LitElement 在 Web 组件/shadowDOM 应用程序中使用大型 css 库(如 bootstrap)的最简单方法是什么?
尝试了以下方法:
寻找在此设置中使用 boostrap 的最简单方法。
LitElement 推荐的向组件添加样式的方法是通过属性styles。以这种方式加载外部.css文件并不简单,但有一些解决方案。
道路import
如果您对“最简单方法”的定义包括使用转译器或模块捆绑器,那么您可以使用非 js 内联导入来完成类似以下的操作:
import bootstrap from './path/to/bootstrap.css';
// ...
class MyElement extends LitElement {
static styles = bootstrap; // If your build system already converted
// the stylesheet to a CSSResult
static styles = unsafeCss(bootstrap); // If bootstrap is plain text
}
Run Code Online (Sandbox Code Playgroud)
有许多专门用于此目的的插件:例如参见babel-plugin-inline-import、rollup-plugin-lit-css、 rollup-plugin-postcss-lit、webpack-lit-loader。
包装方式
如果您想让事物(几乎)保持无构建,您可以编写一个简单的postinstall脚本来生成一个.js导出 lit-ified 样式的文件:
// bootstrap.css.js
import {css} from 'lit-element';
export const bootstrap = css`
<bootstrap here>
`;
// my-element.js
import {bootstrap} from './bootstrap.css.js';
class MyElement extends LitElement {
static styles = bootstrap;
}
Run Code Online (Sandbox Code Playgroud)
关于 Shadow DOM
如果你想使用 Shadow DOM,你必须在每个需要使用它的组件中导入该库,甚至是嵌套组件。这并不像看起来那么繁重,这要归功于Lit 在幕后使用的可构造样式表;将其视为组件加入样式上下文的一种方式,而不是相同样式表的复制。此外,为了让事情井井有条,您可以创建一个“基本”组件来导入引导程序并在需要的地方扩展它:
import bootstrap from 'path/to/bootstrap.css';
export class BaseElement extends LitElement {
static styles = bootstrap;
}
class MyElement extends BaseElement {
render() {
// Bootstrap is ready to use here!
return html``;
}
}
Run Code Online (Sandbox Code Playgroud)
有关样式共享的 Lit 文档:https://lit.dev/docs/components/styles/#sharing-styles
| 归档时间: |
|
| 查看次数: |
6592 次 |
| 最近记录: |