svelte
svelte copied to clipboard
Add a svelte compilation option that guarantees a component only has a single root DOM node or component.
Describe the problem
If I see a component being used with a syntax that indicates it is more or less just like any other built-in DOM node, then I expect it to actually fulfill all of the same basic requirements that a DOM node would have. Components that have more than 1 root DOM node in their markup are a code smell to me.
For example, if you have a "container" like a <div>
, then I would generally expect that placing that component in the tree will insert a single node into the DOM, alongside whatever descendants it might have to help manage its contents. However, there is nothing in the tooling that ensures that such an expectation is maintained.
// Container.svelte
<script>
export let title = "";
</script>
<h3>{title}</h3> <!-- node 1 -->
<div> <!-- node 2 -->
<slot></slot>
</div>
// App.svelte
<body> <!-- Expected to have 1 child, but actually has two -->
<Container title="hello">
<p>testing</p>
</Container>
</body>
Obviously, this is something that can easily be enforced manually with code reviews if that's all you want, but it would be convenient if that kind of stuff could just be off-loaded to the tooling that builds the code.
Describe the proposed solution
I would like to see some sort of compiler option that I could configure globally for my project that would ensure that all components are required to have only a single top-level node in their markup.
Alternatives considered
The only other thing I can think of to do this (and which I could probably figure out how to do if I dove in and tinkered with it) would be to implement a Svelte preprocessor plugin that makes the check for me and then just publish it separately. But given that this seems like something that betrays core expectations for the object model, I get the feeling it would be better implemented as a supported feature in the core tool rather than as an optional, separately installed plugin.
Importance
nice to have
Svelte has no opinion on how many dom nodes there should be in the root of a component.
The cleanest solution is most likely to implement an ESLint rule for this! I believe this project can help you achieve your goals @willnationsdev: https://github.com/ota-meshi/svelte-eslint-parser