Vite as an alternative to webpack-encore in Symfony applications

By Yves Maerschalck

6 min read

Vite (French word for "quick", pronounced /vit/, like "veet") is the fastest frontend build tool at the moment. Webpack-encore integrates perfectly with symfony applications. What if we could have both

Vite as an alternative to webpack-encore in Symfony applications
Authors

Whenever you create a new Symfony application, there will be a moment you have to set up your frontend tooling to build your CSS and JavaScript. The easiest way to do this would be to just follow the instructions on the Symfony docs. This will set up Webpack-encore for you, which is a great way to build frontend code inside your Symfony project.

But sometimes you may want something different. You've heard a lot of good things about Vite, you maybe went to a conference where everybody seemed to be using this tool. Or maybe you just want to join all the cool kids and use the hottest tool of the moment.

All examples used in this blogpost will be using Vue, but Vite can be used with a variety of frameworks.

The following setup will only be usefull for developers who work in a hybrid symfony/javascript environment where you render your page in twig and you spawn your SPA or Vue component on this page.

Why would you want to replace Webpack with Vite?

Webpack is a bundler-based build tool, which means that to serve your application, it needs to crawl, process, and concatenate your application’s entire JavaScript file. This applies to the dependencies and the application code that you write. This is the reason why it takes the webpack dev-server quite a long time to start up. With large applications, starting times can take up to 10 minutes.

Whenever you save a file, the whole JavaScript bundle will be rebuilt by Webpack, which is why the change can take up to 10 seconds to be reflected in the browser, even with HMR enabled. The slow feedback loop caused by Webpack creates a bad developer experience for developers working on large-scale JavaScript applications.

Vite on the other hand leverages the availability of ES Modules in the browser and compile-to-native bundler tools like esbuild.

The use of ES Modules allows you to run a JavaScript application on the browser without having to bundle them together. Esbuild is a JavaScript bundler written in Go that performs 10–100x faster than Webpack.

While a bundler-based workflow like Webpack will have to process your entire JavaScript modules before a single browser request, Vite only processes your dependency modules before a single browser request.

Scaffolding a Vue app with Vite

When creating a new app, you can do this the vite-way or the vue-way. Or with the following commands:

With Vite:

npm create vite@latest

With Vue:

npm init vue@latest

If you are building a Vue app, I recommend the latter. This way allows you to add dependencies like Typescript support, Pinia, Vitest, ... out of the box. After creating the app and installing the dependencies, you can execute npm run dev and your app will be available for coding and thanks to Hot Module Replacement every change will be pushed to the browser instantly.

And this is where Vite really shines. You can read more about the speed of Vite on the documentation website.

A little about webpack-encore

When using webpack-encore, we have several helper functions available to include our build javascript and css files in our twig files

{{ encore_entry_link_tags('app') }}

which will create the following html-tag:

<link rel="stylesheet" href="{{ asset('build/app.123680sd32.css') }}" />

and

{{ encore_entry_link_tags('app') }}

which creates

<script src="{{ asset('build/app.123680sd32.js') }}"></script>

Under the hood, encore will use a manifest file to map entry points with the correct source file. Thanks to this way of working, we don't have to worry about old cached files with the same name.

How about Vite?

If you created your app with Vite, there will be an index.html file where you can find the following script tag:

<script type="module" src="/src/main.js"></script>

Now, this works great when using the Vite dev-server, but if you just copy/paste this code into your twig-file, you'll only get a 404 - file not found - error. So the first thing we'll have to create will be a twig extension that we can use like we did with webpack encore:

For JavaScript:

{{ vite_asset_js('main') }}

And likewise for CSS:

{{ vite_asset_css('main') }}

Creating the Twig extension

In the Twig extension folder (normally src/Twig/Extension), we'll create a new class

This example uses .ts files. Just change this to .js if you don't use Typescript
<?php

namespace MyApp\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class ViteAssetExtension extends AbstractExtension
{
    private bool $isDev;
    private string $manifest;

    public  function __construct(string $env, string $manifest)
    {
        $this->isDev = $env === 'DEV';
        $this->manifest = $manifest;
    }

    public function getFunctions()
    {
        return [
            new TwigFunction(
                'vite_asset_js',
                [$this, 'getAssetJs'],
                ['is_safe' => ['html']]
            ),
            new TwigFunction(
                'vite_asset_css',
                [$this, 'getAssetCss'],
                ['is_safe' => ['html']]
            ),
        ];
    }

    public function getAssetJs(string $entry)
    {
        if ($this->isDev) {
            return $this->getAssetDevJs($entry);
        }

        return $this->getAssetProdJs($entry);
    }

    public function getAssetCss(string $entry)
    {
        if(!$this->isDev) {
            return $this->getAssetProdCss($entry);
        }
        return '';
    }

    public function getAssetProdJs(string $entry)
    {
        $data = json_decode(file_get_contents($this->manifest), true);
        $file = $data['src/'.$entry.".ts"]['file'];

        $html = <<<HTML
<script type="module" src="/frontend/{$file}"></script>
HTML;

        return $html;
    }

    public function getAssetProdCss(string $entry)
    {
        $data = json_decode(file_get_contents($this->manifest), true);

        if (!array_key_exists('css', $data['src/'.$entry.".ts"])) {
            return '';
        }

        $css = $data['src/'.$entry.".ts"]['css'];

        $html = '';

        foreach ($css as $cssFile) {
            $html .= <<<HTML
<link rel="stylesheet" media="screen" href="/frontend/{$cssFile}" />
HTML;
        }

        return $html;
    }

    public function getAssetDevJs(string $entry)
    {
        return <<<HTML
<script type="module" src="http://localhost:3000/@vite/client"></script>
<script type="module" src="http://localhost:3000/src/{$entry}.ts"></script>
HTML;

    }


}

Dev mode

When you have your Vite dev-server running, we will only inject the javascript entry because this will also import the necessary styles. We will have to load both the Vite client and the entrypoint file:

<script type="module" src="http://localhost:3000/@vite/client"></script>
<script type="module" src="http://localhost:3000/src/{$entry}.ts"></script>

If you want to make this extension even better, you could opt to put the dev-server URL in an environment variable, but for now, you get the idea. You can now use the helper function

{{ vite_asset_js('main') }}

in your twig file and the javascript app with the entrypoint main.js will be loaded and executed inside your twig source code. Don't forget to also add the div with the correct id inside this file:

<div id="app"></div>

You now have a working Vue app inside your Symfony rendered page where you can use all the advantages of the fast Vite tooling.

Prod mode

If we want to deploy our app to production, we will first have to build it. Normally when building a Vite app, the build process will create a dist folder inside the app folder. We'll have to edit our vite.config.ts (or .js) to alter this behaviour.

import { fileURLToPath, URL } from 'url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import svgLoader from 'vite-svg-loader'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), svgLoader()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  build: {
    manifest: true,
    assetsDir: '',
    outDir: '../../web/frontend',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: './src/main.ts',
      },
    },
  },
})

Make sure the outDir is the same as the one you used in the Twig extension. In this example we've opted to empty the output dir on each build, but this is not necessary.

One build, multiple apps

In a hybrid environment like this, it's likely that you're not building one large Vue app, but probably multiple smaller ones to use as components on a twig-rendered page. In theory, you could scaffold each and every one of these apps in its own folder, but this is not really maintainable. You could also decide not to build your apps as standalone apps, but more as web components or something, but that's not the scope of this article.

Normally when you create your Vite project, you'll get a file structure as following:

- src
    - main.ts
- public
- index.html
- package.json
- vite.config.ts
...

To build multiple apps, you just have to create a folder for each app and put an index.html inside it

- app1
    - index.html
- app2
    - index.html
- src
    - main.ts
    - app1.ts
    - app2.ts
- public
- index.html
- package.json
- vite.config.ts
...

Then, in your vite.config.ts, you can add them to your input files:

{
    rollupOptions: {
      input: {
        'main': './src/main.ts',
        'app1': './src/app1.ts',
        'app2': './src/app2.ts'
      }
    }
}

Best of both worlds

If you are working on a project with a team of frontend- and backend developers, this way of working might be very interesting. The frontenders will be able to develop Vue apps outside of Symfony. Because your are still running your dev-server during development, it'll still be possible to just surf to https://localhost:3000 and just develop your frontend like you normally do. When using multiple apps, just navigate to https://localhost:3000/app1/ (don't forget the trailing slash) and you're set.

Let me know what works for you. All tips and tricks are welcome!


Upcoming events

  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋‍♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design

Share