Skip to main content

It would be impractical to put your entire app in a single component. Instead, we can import components from other files and then use them as though we were including elements.

We now present you 2 files in the editor on the right (upper bar) to click on, App.svelte and Nested.svelte.

Each .svelte file holds a component that is a reusable self-contained block of code that encapsulates HTML, CSS, and JavaScript that belong together.

Let's add a <script> tag to App.svelte that imports the file (our component) Nested.svelte into our app...

<script>
	import Nested from './Nested.svelte';
</script>

...then use component Nested in the app markup:

<p>This is a paragraph.</p>
<Nested />

Notice that even though Nested.svelte has a <p> element, the styles from App.svelte don't leak in.

Also notice that the component name Nested is capitalised. This convention has been adopted to allow us to differentiate between user-defined components and regular HTML tags.

App.svelte
Nested.svelte
<p>This is a paragraph.</p>

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>

/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
append_styles,
attr,
detach,
element,
init,
insert,
noop,
safe_not_equal
} from "svelte/internal";

import "svelte/internal/disclose-version";

function add_css(target) {
append_styles(target, "svelte-urs9w7", "p.svelte-urs9w7{color:purple;font-family:'Comic Sans MS', cursive;font-size:2em}");
}

function create_fragment(ctx) {
let p;

return {
c() {
p = element("p");
p.textContent = "This is a paragraph.";
attr(p, "class", "svelte-urs9w7");
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(p);
}
}
};
}

class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {}, add_css);
}
}

export default App;
result = svelte.compile(source, {
generate:
css:
});
p.svelte-urs9w7{color:purple;font-family:'Comic Sans MS', cursive;font-size:2em}