当前位置: 首页 > 科技观察

如何像导入JS模块一样导入CSS?

时间:2023-03-14 12:42:12 科技观察

在刚刚发布的Chrome93版本中更新了一个令人兴奋的新功能:CSSModuleScript,您可以使用它像导入JavaScript模块一样加载CSS样式。然后,你可以像ConstructableStylesheet一样,将CSS样式应用到document和shadowdom上,比其他加载CSS的方式更方便、更高效。什么是可构造样式表?在了解CSSModuleScript之前,我们先了解什么是ConstructableStylesheet。和表面意思一样,是为直接构建CssStyleSheet而设计的,在document和shadowdom下都可以使用。使用可构造样式表:通过newCSSStyleSheet()构造样式表更改可构造样式表使用adoptedStyleSheets使用可构造样式表更改可构造样式表有以下API:insertRule(rule,index)insertruleintocssRulesattributedeleteRule(rule,index)removerulefromcssRulesattributereplace(text)异步替换cssRulesreplaceSync(text)同步替换//ConstructtheCSSStyleSheetconststylesheet=newCSSStyleSheet();//AddsomeCSSstylesheet.replaceSync('body{background:#000!important;}')//ORstylesheet.replace,返回一个Promiseinstead//Tellthedocumenttoadoptyournewstylesheet.//NotthatthisalsoworkswithShadowRoots.document.adoptedStyleSheets=[...document.adoptedStyleSheets,stylesheet];使用CSSModuleScript导入CSSdromshatsport,导入如下:'./styles.css'assert{type:'css'};document.adoptedStyleSheets=[sheet];shadowRoot.adoptedStyleSheets=[sheet];CSSModuleScript默认导出一个可构建的样式表,不像其他任何可构建的样式表样式表,它对document和shadowdom使用采用的样式表。与使用JavaScript导入CSS的其他方式不同,您不需要创建

Thisdivwillhaveagreenborderbutnobackgroundcolor.
目前暂不支持Firefox和Safari浏览器,但未来可期~