Reputation: 2195
I'm using webpack and the extract-text-webpack-plugin to bundle a webcomponent (created using preact-custom-element) and its style.
I'm able to use the component successfully in a separate html file like so:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div>
<script async src="./webcomponent.js" type="text/javascript"></script>
<custom-menu name="Test"></custom-menu>
</div>
</body>
</html>
The custom-menu
tag is my webcomponent. It shows the styled custom component as expected.
However, I want to know if there is a possibility to apply my custom CSS (inserted using the extracted styles.css
file) only to the custom element and not allowing the style to potentially overwrite other styles belonging to html elements outside the webcomponent.
My webpack config:
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: {
webcomponent: './lib/menu/menu-panel-webcomponent-controller.widget.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
output: {
path: path.resolve(__dirname, 'widget/')
},
plugins: [
new ExtractTextPlugin("styles.css")
]
};
It takes my custom component menu-panel-webcomponent-controller.widget.js
and applies the extract
function of the ExtractTextPlugin
to all css files. The resulting bundle alongside the style styles.css
is then found inside the widget/
directory.
Upvotes: 0
Views: 2439
Reputation: 1
this is work with only css this feature is not change class name in html
Upvotes: 0
Reputation: 2195
Here is what I found:
I found preact shadow dom which allows the implementation of a shadow DOM. A shadow DOM allows scoped CSS, which means that the CSS is only bound to the component and can neither be influenced from the outside nor can it leak outside its scope.
However, note that MS Edge has currently no support for shadow DOM (see their roadmap).
I also found that local CSS scoping can be done using webpack only as well. See https://github.com/webpack-contrib/css-loader. However, the loader explicitly replaces local selectors with unique identifiers.
Example:
:local(.className) {
background: red;
}
results in:
._23_aKvs-b8bW2Vg3fwHozO {
background: red;
}
Upvotes: 1