Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3056

New in Symfony 3.3: Manifest-based asset versioning

$
0
0
Ryan Weaver

Contributed by
Ryan Weaver in #22046.

One of the main features of the Asset component is the ability to manage the versioning of the application's assets. Asset versions are commonly used to control how these assets are cached. For example, if you define this config for your assets:

1
2
3
4
5
# app/config/config.ymlframework:# ...assets:version:'v2'

And use the asset() function to reference your assets in the templates:

1
<img src="{{asset('images/logo.png')}}" />

Then, the URL generated for the image will be /images/logo.png?v2. This is managed by the StaticVersionStrategy class, which is one of the built-in versioning strategies provided by Asset.

The static strategies that append some changing values to the query string are becoming less and less popular, so developers need tocreate a custom versioning strategy to keep up with the latest trends in asset versioning.

That's why in Symfony 3.3 we've decided to add a new versioning strategy based on a JSON file manifest. This is the strategy used by popular tools such asWebpack, which generate a JSON file mapping all source file names to their corresponding output file. For example:

1
2
3
4
5
{"css/app.css":"build/css/app.b916426ea1d10021f3f17ce8031f93c2.css","js/app.js":"build/js/app.13630905267b809161e71d0f8a0c017b.js""...":"..."}

The random-looking part of the paths is called "chunk hash" in Webpack and it's a hash of the file contents. This is the best strategy for long-term asset caching, because the hash, and therefore the asset path, will change as soon as you make any change in the asset file, busting any existing cache.

In order to use this strategy in a Symfony application, define the newjson_manifest_path asset config option:

1
2
3
4
5
# app/config/config.ymlframework:# ...assets:json_manifest_path:'%kernel.root_dir%/../web/build/manifest.json'

Then, keep using the asset() function as before:

1
<link href="{{asset('/css/app.css')}}">

The new version strategy will turn that link into <link href="/build/css/app.b916426ea1d10021f3f17ce8031f93c2.css"> and it will update it as soon as you change the original asset file.


Be trained by Symfony experts - 2017-04-03 Paris - 2017-04-04 London - 2017-04-04 London

Viewing all articles
Browse latest Browse all 3056

Trending Articles