Loading only needed selectors of a given CSS library into web component as a constructable stylesheet.
npm install constructable-style-loaderconstructable stylesheet.
CSSStyleSheetObject JavaScript object, which can be adopted to an element using adoptedStyleSheets setter.
postcss-loader when need to use output from other CSS preprocessors.
postcss-loader, then also consider postcss-discard-comments plugin to delete unnecessary comments
constructable-style-loader:
console
npm install --save-dev constructable-style-loader
`
Then add the loader to your webpack config. For example:
style.css
`css
.panel {
background-color: orange;
border-style: solid;
}
`
panel.js
`js
import style from './style.css';
class Panel extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"});
this.shadowRoot.innerHTML = ;
this.shadowRoot.adoptedStyleSheets = [style]
}
}
if (customElements.get('ata-panel') == null) {
customElements.define('ata-panel', Panel);
}
`
webpack.config.js
`js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['constructable-style-loader'],
},
],
},
};
`
Optional usage with purgecss
Loader options accept object that will be passed to purgecss plugin (assuming it is installed), if {purge: true} property is present.
webpack.config.js
`js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: 'constructable-style-loader',
options: {
purge: true,
content: ['*/.js'],
safelist: ['white-listed']
}
},
]
},
],
},
};
`
If constructable-style-loader is chained after post-loader`, purgecss will be given AST root from PostCSS