sveltejs / svelte

Cybernetically enhanced web apps

Home Page:https://svelte.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nested child components lose their css when the parent is used as a custom element

TehShrike opened this issue · comments

The setup: I'm exporting a component as a custom element with css: true. That component makes use of a nested component. That nested component has its own <style> tag.

If you check out this REPL example and flip on the css and customElement compiler toggles, you'll see the relevant output.

The problem

I expect those styles to be applied when I use the <x-app></x-app> parent component, but h1 { color: green; } never shows up in the document.

Why

You can see in the JS output that the App component instantiates the child component using new Nested({}). However, since that Nested (HTMLElement) never gets actually inserted into the document, its shadowRoot never makes it into the document.

Since the custom-element-generated component injects css in the constructor using

this.shadowRoot.innerHTML = `<style>h1{color:green}</style>`;

that means that the nested component's styles never make it into the document, and all their CSS is not applied.

What should be done

I don't know. :-x

Other potentially-relevant issues

#3520 has to do with nested custom elements, #4124 has to do with custom elements compiled with css: false.

You can sort of work around it with this Rollup plugin

import pify from 'pify'
import fs from 'fs'
const { readFile, writeFile } = pify(fs)

const transformCeCss = async (file) => {
	const code = await readFile(file, { encoding: 'utf8' })
	const transformed = transform(code)
	await writeFile(file, transformed)
}

const assignment = 'this.shadowRoot.innerHTML = '

const transform = code => {
	const parts = code.split(assignment)
	let aggregated = ''
	const partsWithOnlyOneStyle = parts.map((part, i) => {
		const withoutAnyStyleString = part.replace(/^`<style>(.+?)<\/style>`;/, (_,css) => {
			aggregated += css
			return ''
		})

		if (i === parts.length - 1) {
			return assignment + '`<style>' + aggregated + '<style>`;' + withoutAnyStyleString
		}

		return withoutAnyStyleString
	})

	return partsWithOnlyOneStyle.join('')
}

//...

export default {
	output: {
		file: outputPath,
	},
	plugins: [
		svelte({
			css: true,
			customElement: true,
		}),
		{
			writeBundle() {
				// https://github.com/sveltejs/svelte/issues/4274
				transformCeCss(outputPath).catch(err => {
					console.error(err) // eslint-disable-line no-console
				})
			}
		}
	]
}

it rolls up all the component styles so they all get applied at the top.

You lose component style scoping, though.

I just created a template for using Svelte and web components interchangeably in a codebase. And also comes with Storybook and i18n configured.
More info: https://github.com/redradix/svelte-custom-element-template

I've just run into this issue.

EDIT: just understood the REPL from your comments.

I was using that @TehShrike's Rollup plugin, which worked for a few days, but now, suddenly, the CSS is lost for one of the nested components.

So it seems like this is something that should be fixed in Svelte?

Seems that some HML+ CSS combo was the reason in that component.

The offending CSS was missing a semicolon in the last rule (should work).

// hack: custom-elment with sub comonents will lose style, manual set it
let elm = document.quqerySlector("xx-element")
function setShadowStyle(host, styleContent) {
	var style = document.createElement( 'style' )
	style.innerHTML = styleContent;
	host.shadowRoot.appendChild( style );
}
setShadowStyle(elm, '@import "./build/component.css"');
commented

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

hi
in 2023 no fix for this bug ? not even with svetkit ?

Just encountered this as well. As this seems to be a default behaviour, it would've been nice to have a disclaimer added to https://svelte.dev/docs#run-time-custom-element-api, at least I do not see this restriction there.

Closed via #8457, to be released in Svelte 4