Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 62 ยท Templates with Twig

Assets, AssetMapper and Webpack Encore

Ship CSS, JavaScript and images in Symfony with AssetMapper and import maps, the asset() function, Tailwind, Stimulus and Turbo, and know when Webpack Encore fits.

A website is more than HTML: it needs stylesheets, JavaScript and images, and browsers should cache them for as long as possible without ever showing a stale copy. Symfony gives you two supported ways to handle this. AssetMapper is the modern default: no Node.js, no bundler, no build step in development. Webpack Encore wraps Webpack for projects that need compilation, such as React with JSX or large TypeScript code bases.

This lesson explains how AssetMapper turns your files into versioned URLs and an import map, how the asset() function fits in, and how Tailwind, Stimulus and Turbo plug in. Everything that touches the real framework is shown read-only, because Symfony cannot run on this site. The two runnable examples are small PHP stand-ins that reproduce the core ideas: digested file names and an import map.

The problem: caching versus freshness

If app.css is served at /app.css with a long cache lifetime, a returning visitor keeps the old file after you deploy. If you serve it with no cache, every page view downloads it again. The classic solution is cache busting: put a fingerprint of the file's content into its URL, such as /assets/app-3f9a1c2e.css. The URL changes exactly when the content changes, so you can tell browsers to keep the file for a year.

AssetMapper does this for you. You keep your source files in the assets/ directory of the project. When a template asks for app.css, the bundle returns a URL with the content digest in it.

flowchart LR
    A["assets/styles/app.css"] --> M["AssetMapper<br/>computes content digest"]
    M --> U["/assets/styles/app-3f9a1c2e.css"]
    T["Twig: asset('styles/app.css')"] --> M
    U --> B["Browser caches it for a year"]

A content digest in the URL lets the browser cache files forever: changing a file changes its URL.

The next example is a stand-in for that mechanism. It is not the real AssetMapper (which also handles import rewriting, vendor packages and compression), but the idea is identical: digest the content, insert it before the extension.

PHP Digested asset URLs (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that editing the CSS changed its URL while the untouched logo kept the same one, so returning visitors re-download only what changed.

Setting up AssetMapper

A webapp project already contains it. In a skeleton you add it with Composer:

Terminal
composer require symfony/asset-mapper symfony/asset symfony/twig-pack

The recipe creates an assets/ directory with app.js and a stylesheet, a config/packages/asset_mapper.yaml file and an importmap.php file. The YAML tells the bundle which directories to expose:

YAML
# config/packages/asset_mapper.yaml
framework:
    asset_mapper:
        paths:
            - assets/

Your base template then loads both entry points:

TWIG
{# templates/base.html.twig #}
<head>
    <link rel="stylesheet" href="{{ asset('styles/app.css') }}">
    {% block javascripts %}
        {% block importmap %}{{ importmap('app') }}{% endblock %}
    {% endblock %}
</head>

asset('styles/app.css') returns the digested URL. importmap('app') prints an import map plus a small script that imports the app entry point. Images work the same way: <img src="{{ asset('images/logo.svg') }}">.

In development, AssetMapper serves the files on demand, so you edit a file and reload. For production you compile once during deployment:

Terminal
php bin/console asset-map:compile

That writes every file with its digest in the name to public/assets/ along with a manifest, so the web server can serve them as static files and PHP is not involved. Two other commands are worth knowing: php bin/console debug:asset-map lists everything the mapper knows about, and php bin/console importmap:audit checks your JavaScript packages for known vulnerabilities.

Import maps: JavaScript without a bundler

Modern browsers understand ES modules (import ... from ...) natively. The missing piece is bare imports such as import confetti from 'canvas-confetti', which the browser cannot resolve to a URL by itself. An import map is a JSON object in the page that tells it where each name lives. importmap.php is Symfony's source of truth for that JSON:

PHP
<?php
// importmap.php
return [
    'app' => [
        'path' => './assets/app.js',
        'entrypoint' => true,
    ],
    'canvas-confetti' => [
        'version' => '1.9.3',
    ],
];

You manage third-party packages with commands, not by editing this file:

Terminal
php bin/console importmap:require canvas-confetti   # download and register
php bin/console importmap:update                    # newer versions
php bin/console importmap:remove canvas-confetti
php bin/console importmap:install                   # restore vendor files after a clone

importmap:require downloads the package into assets/vendor/, so in production your visitors never contact a third-party CDN. In your own code you import it like in any modern project:

JavaScript
// assets/app.js
import './styles/app.css';
import confetti from 'canvas-confetti';

document.querySelector('#party')?.addEventListener('click', () => confetti());

Even import './styles/app.css' works: AssetMapper turns it into a <link> for the stylesheet.

PHP Generating an import map (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the real structure: an object under imports that maps each module name to a digested URL, followed by a module script that starts the app entry point.

Import maps need no build step, but they also cannot compile JSX, TypeScript or Vue single-file components. For those you need a compiler: either Encore or a separate Vite setup.

Tailwind, Sass and other preprocessors

CSS that must be generated is handled by small bundles that run next to AssetMapper. The Tailwind bundle (symfonycasts/tailwind-bundle) downloads the standalone Tailwind CLI, so Node.js is still not required:

Terminal
composer require symfonycasts/tailwind-bundle
php bin/console tailwind:init
php bin/console tailwind:build --watch     # while developing
php bin/console tailwind:build --minify    # in your deployment script

The bundle reads your templates, produces one CSS file and AssetMapper versions it like any other. A Sass bundle works the same way. In production, run tailwind:build before asset-map:compile, so the compiled file exists when the mapper fingerprints everything.

Stimulus and Turbo

Two small libraries from the Hotwire family give you interactivity without a front-end framework.

Stimulus attaches behavior to HTML through data- attributes. The symfony/stimulus-bundle auto-registers every file in assets/controllers/:

JavaScript
// assets/controllers/hello_controller.js
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ['name', 'output'];

    greet() {
        this.outputTarget.textContent = `Hello, ${this.nameTarget.value}!`;
    }
}
TWIG
<div data-controller="hello">
    <input data-hello-target="name" type="text">
    <button data-action="click->hello#greet">Greet</button>
    <p data-hello-target="output"></p>
</div>

Turbo (symfony/ux-turbo) makes link clicks and form submissions feel instant: it fetches the next page in the background and swaps the <body>, so the browser does not reload CSS and JavaScript. Turbo Frames update only part of the page, and Turbo Streams let the server push small HTML updates after a form post. Your controllers stay normal Symfony controllers that return HTML.

Webpack Encore

Encore is the older option and still fully supported. It uses Node.js, npm and a webpack.config.js:

JavaScript
// webpack.config.js
const Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('app', './assets/app.js')
    .enableSassLoader()
    .enableReactPreset()
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction());

module.exports = Encore.getWebpackConfig();
TWIG
{{ encore_entry_link_tags('app') }}
{{ encore_entry_script_tags('app') }}

You build with npm run dev, npm run watch or npm run build. Choose Encore when you need JSX, TypeScript, Vue single-file components or complex code splitting; choose AssetMapper for the typical server-rendered site. Both can even be mixed during a migration, since each only owns the files you give it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does AssetMapper put a digest of the file's content into the URL?

    The URL changes exactly when the content changes, which makes very long cache lifetimes safe. It is cache busting, not security or compression.
  2. 2. Which command prepares the files for production so a web server can serve them statically?

    asset-map:compile writes the digested files and a manifest to public/assets/. importmap:install only restores downloaded vendor packages.
  3. 3. What does an import map solve?

    Browsers support ES modules natively but cannot resolve bare names on their own. The import map is the JSON lookup table that provides the URLs.
  4. 4. When is Webpack Encore the better choice than AssetMapper?

    AssetMapper serves files as they are and has no compiler. Encore (Webpack) is for projects that must compile code. AssetMapper is not deprecated and needs no Node.js.

Summary

  • AssetMapper exposes the assets/ directory, puts a content digest into each URL and needs no Node.js or build step.
  • Use asset('path') in Twig for files and importmap('app') for JavaScript entry points.
  • importmap.php lists your modules; manage third-party ones with importmap:require, importmap:update and importmap:install.
  • Deploy with asset-map:compile (after tailwind:build if you use Tailwind).
  • Stimulus adds behavior through data- attributes and Turbo speeds up navigation, both with no custom front-end framework.
  • Choose Webpack Encore when you need to compile JSX, TypeScript or similar.

Next, you leave templates behind and look at how Symfony builds and connects objects: Services and the Service Container.