293 words
1 minutes
Quick Start with Svelte and Symfony

I’ve been wanting to seriously get into Svelte for a while now, yet another JavaScript library that has been around for several years and has gained significant traction since 2019 with version 3.

Some of its strengths include simple, lightweight code with a learning curve similar to Vue.js. Here, there’s no need to manipulate the DOM—Svelte takes care of it for you!

And finally, in terms of performance, this library is among the fastest on the market.

Create a Symfony Project#

Let’s start by creating our Symfony project—super easy:

symfony new svelte

At the time of writing this, Symfony 6 is not yet available. So, we’ll be working with version 5.3. Let’s install everything we need for the front-end:

composer req twig
composer req symfony/webpack-encore-bundle

And since we’re lazy, we’ll use the Maker Bundle:

composer req doctrine/annotations
composer req --dev symfony/maker-bundle

Create a controller that will display Svelte:

bin/console make:controller

Install Svelte and Webpack#

To install Svelte and Webpack, add svelte-loader:

yarn install
yarn add svelte-loader svelte

In the webpack.config.js file, remove everything related to Stimulus:

.enableStimulusBridge('./assets/controllers.json')

Then add the loader for Svelte:

.addLoader({
    test: /\.svelte$/,
    loader: 'svelte-loader',
}, {
    test: /node_modules\/svelte\/.*\.mjs$/,
    resolve: { fullySpecified: false }
})

Replace the following line:

module.exports = Encore.getWebpackConfig();

With:

let config = Encore.getWebpackConfig();
config.resolve.mainFields = ['svelte', 'browser', 'module', 'main'];
config.resolve.extensions = ['.mjs', '.js', '.svelte'];

let svelte = config.module.rules.pop();
config.module.rules.unshift(svelte);

module.exports = config;

Add Svelte to the Project#

In the default/index.html.twig file, add:

{% block stylesheets %}
    {{ encore_entry_link_tags('app') }}
{% endblock %}

{% block javascripts %}
    {{ encore_entry_script_tags('app') }}
{% endblock %}

Create the assets/app.js file:

import App from './App.svelte';

const app = new App({
    target: document.body,
});

Create the component assets/App.svelte:

<script>
    let count = 0;
    $: doubled = count * 2;

    function handleClick() {
        count += 1;
    }
</script>

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>

Compile with:

yarn dev

Result#

Press F5, and here’s the result! 🎉

Enjoy!