Symfony Webpack Encore Bundle

repository·2.x·Indexed 21 days ago

https://github.com/symfony/webpack-encore-bundle

Integration between Symfony and Webpack Encore for managing and rendering frontend assets. It provides the EntrypointLookup service to retrieve compiled JavaScript and CSS files from entrypoints.json, supports Webpack's splitEntryChunks feature, and includes a TagRenderer for generating HTML <script> and <link> tags with support for Subresource Integrity (SRI).

Tokens
1.8K
Snippets
5
Records
8
Agent score
76%

What's inside webpack-encore-bundle

  1. Use Webpack Encore's splitEntryChunks feature in Symfony

    2.x
    The WebpackEncoreBundle enables Symfony to support the splitEntryChunks() feature from Webpack Encore. It works by reading an entrypoints.json file generated by Webpack and automatically rendering the necessary dynamic <script> and <link> tags for your assets. This allows for more efficient asset loading through code splitting.
  2. Retrieve list of rendered assets

    2.x

    You can retrieve a list of all assets rendered during the current request using getRenderedScripts() and getRenderedStyles(). This is useful for managing asset loading order or performing debugging.

    By default, these methods return an array of file paths (strings). If you pass true to the $includeAttributes parameter, they will return an array of associative arrays containing the full attribute sets for each asset.

    // Get just the URLs of rendered scripts
    $scripts = $tagRenderer->getRenderedScripts();
    // Result: ['/build/app.js', '/build/vendor.js']
    
    // Get the full attribute maps for rendered styles
    $styles = $tagRenderer->getRenderedStyles(true);
    // Result: [['rel' => 'stylesheet', 'href' => '/build/app.css', ...], ...]
  3. Render Webpack Encore script and link tags

    2.x

    The TagRenderer service is used to generate the HTML <script> and <link> tags required to load your Webpack Encore entrypoints in Twig templates or directly in PHP.

    It automatically handles asset paths, integrity hashes (if available), and allows for custom attributes. You can specify a specific entrypoint name (defaulting to _default) and provide extra attributes like async or defer via the $extraAttributes array.

    // To render <script> tags for a JavaScript entrypoint
    $scriptTags = $tagRenderer->renderWebpackScriptTags(
        'app',             // entryName
        null,               // packageName (optional)
        '_default',         // entrypointName (optional)
        ['defer' => true]  // extraAttributes
    );
    
    // To render <link> tags for a CSS entrypoint
    $linkTags = $tagRenderer->renderWebpackLinkTags(
        'app',             // entryName
        null,               // packageName (optional)
        '_default',         // entrypointName (optional)
        ['class' => 'js-app-style'] // extraAttributes
    );
  4. Reset rendered asset state

    2.x

    The TagRenderer implements ResetInterface. Calling reset() clears the internal lists of renderedFiles and renderedFilesWithAttributes for both scripts and styles. This is typically used by Symfony's kernel to ensure that asset tracking does not leak between different requests in long-running processes.

    $tagRenderer->reset();
  5. Retrieve entrypoint lookups with getEntrypointLookup()

    2.x

    The EntrypointLookupCollection allows you to retrieve an EntrypointLookupInterface instance for a specific Webpack build.

    If you call getEntrypointLookup() without an argument, the collection will attempt to use the configured defaultBuildName. If no build name is provided and no default build is configured, an UndefinedBuildException is thrown. If a specific build name is provided that does not exist in the container, an UndefinedBuildException is also thrown.

    // If a default build is configured, you can call it without arguments:
    $entrypointLookup = $collection->getEntrypointLookup();
    
    // Or specify a specific build name:
    $entrypointLookup = $collection->getEntrypointLookup('my_custom_build');
  6. Use EntrypointLookup methods

    2.x

    The EntrypointLookup class provides the following public API for interacting with entrypoint data:

    • getJavaScriptFiles(string $entryName): array: Returns an array of file paths for the JavaScript assets of the given entry.
    • getCssFiles(string $entryName): array: Returns an array of file paths for the CSS assets of the given entry.
    • getIntegrityData(): array: Returns the integrity mapping from the entrypoints.json file, used for Subresource Integrity.
    • entryExists(string $entryName): bool: Checks if the specified entrypoint exists in the data.
    • reset(): void: Resets the internal state of the service (clears previously returned files to prevent duplicates in subsequent calls).
  7. Retrieve JavaScript and CSS files for a Webpack entrypoint

    2.x

    The EntrypointLookup service allows you to retrieve the list of compiled JavaScript and CSS files associated with a specific Webpack entrypoint by reading the entrypoints.json file generated by Webpack Encore.

    It supports:

    • Local file paths.
    • Remote URLs (requires symfony/http-client).
    • Caching via Psr\\Cache\\CacheItemPoolInterface.
    • Integrity data retrieval for Subresource Integrity (SRI).

    If an entrypoint is requested that does not exist, it throws an EntrypointNotFoundException when in strictMode (which is enabled by default).

    // Example usage of EntrypointLookup
    $lookup = new EntrypointLookup('/path/to/public/entrypoints.json');
    
    // Get JS files
    $jsFiles = $lookup->getJavaScriptFiles('app');
    
    // Get CSS files
    $cssFiles = $lookup->getCssFiles('app');
    
    // Get integrity data for SRI
    $integrityData = $lookup->getIntegrityData();
  8. Configure EntrypointLookup constructor

    2.x

    The EntrypointLookup constructor accepts several parameters to control how entrypoints are fetched and cached:

    ParameterTypeDescription
    $entrypointJsonPathstringThe path to the entrypoints.json file. Can be a local file path or a URL starting with http.
    $cache?CacheItemPoolInterfaceAn optional PSR-6 cache implementation to cache the parsed JSON data.
    $cacheKey?stringThe cache key to use if a cache is provided.
    $strictModeboolIf true (default), missing files or entries throw exceptions. If false, it returns empty arrays or fails silently.
    $httpClient?HttpClientInterfaceAn optional Symfony HTTP Client. Required if $entrypointJsonPath is a URL.