Svelte has probably one of the most compact syntaxes to import components. All other SPA frameworks seem to demand more code lines.
Let’s have a look at an example. In this example, we have a small component named GreetComponent. This component contains a button, pressing which greets the user with an alert. We’re going to import this component into our App component.
Here’s the code to our GreetComponent.svelte file:
<script>
const pressButton = () => {
alert('Hello!')
}
</script>
<div>
<div class="btn-comp">
<h2>Greet component</h2>
<button on:click="{pressButton}">Greet!</button>
</div>
</div>
<style>
.btn-comp {
border: 1px solid #6100cf;
padding: 10px;
border-radius: 4px;
}
</style>
Code language: HTML, XML (xml)
And here we import it into the App.svelte component as follows:
<script>
import GreetComponent from './GreetComponent.svelte'
</script>
<div>
<h1>App component</h1>
<GreetComponent/>
</div>
Code language: HTML, XML (xml)
In the above file, all we did was use the import statement to import the component. And then we have the component ready to use.
If you’ve worked with React or Vue, you’d notice a difference here. The component we imported here was not even exported anywhere, to begin with! Svelte takes care of it by itself. It means that whenever we create a component, svelte converts the module into an exportable form on its own. However, the exportable code is only executed when we import it into some component.
Here’s what the above example would look like in action: