butopen / web-components-tailwind-starter-kit

How to develop a web component using tailwind - a modern starter kit with vite, lit element, typescript, scss and of course tailwind
MIT License
105 stars 15 forks source link

Style leaks from the components #1

Closed dlin-me closed 1 year ago

dlin-me commented 1 year ago

Hi, appreciate your repo. But styles are leaking into the parent page with your approach.

To show the problem. Add one

to the index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BrowserBot web components</title>
</head>
<body>
<test-component name="Pippo"></test-component>
<test2-component name="Pluto"></test2-component>
<script type="module" src="src/test/test.component.ts"></script>
<script type="module" src="src/test2/test2.component.ts"></script>
<p>This should not be affected, it is</p>
</body>
</html>

The result image

Also, the styles should not be added to the parent html page header. It should be scoped to the components itself.

The problem is that the static style variable needs to be the static property of the web component class itself, not to the parent class.

salvatoreromeo commented 1 year ago

hi @dlin-me , thanks for posting it. I just fixed it as described below:

this behavior depends on how vite handles style imports: by default, vite adds imported styles into the head. to ensure that they are not inserted in the head and solve the problem that you mentioned just add ?inline in the import of the .scss file

so, for instance:

import style from "./test2.component.scss?inline"; // look at the ?inline at the end: it fixes the issue

I just updated the repo too ;-)

image

dlin-me commented 1 year ago

@salvatoreromeo Thank you! This solves the problem.