Asset Bundles

laktek edited this page Nov 11, 2014 · 8 revisions

With Punch you can easily minify and bundle your JavaScript and CSS assets. These are recommended best practices for any web site, since loading time and performance can make significant impact on the user experience.

Defining Bundles

You have to define the bundles in config.json. Here's how a sample bundle configuration would look like:

		"bundles" : {
			"/all.js" : [

			"/all.css" : [

You have to specify a path as the name of the bundle. Bundle will be created at this path in the output directory. Files that need to be included in the bundle should be specified as an array (Punch will look for these paths in the templates directory).

Apart from explicit asset paths, it's possible to give wildcard paths as follows:

		"bundles" : {
			"/css/module.css" : [

In the above example, Punch will create a bundle all available CSS files in templates/css/modules.

Also, you can define nested bundles. Take a look at the example given below:

		"bundles": {
				"/css/module.css": [
				"/css/all.css": [

We have defined the bundle /css/module.css as an asset in /css/all.css bundle. When bundling /css/all.css, Punch will resolve and include the assets defined in /css/module.css.

Note that you can even specify compilable assets such as CoffeeScript and LESS in a bundle. Such assets will be compiled before adding to the bundle.

You should always specify the same type of assets in a bundle (don't mix JavaScript files in a CSS bundle).

Bundle helper tags

There are two special helper tags that you can use in layouts, to call the bundled JavaScript and CSS files.



	<script src="/all-1347328703775.js"></script>




	<link rel="stylesheet" type="text/css" media="screen" href="/all-1347328703775.css">

Bundle helper tags will add a fingerprint (the last-modified date of bundle in Unix time) to the bundle path it outputs. This is useful to bust the caches, if you serve the assets through a content delivery network(CDN).

It is possible to disable fingerprinting from the configuration.

asset_bundling: {
	fingerprint: false

Local Environments

If you are running the Punch server in a local environment (host is localhost, or any domain ending with .local), bundle helper will output tags for individual files in the bundle, instead of the bundled file. This is useful for browser based debugging and inspecting (with Firebug or Chrome DevTools) while on development.

You can add more hosts to treat as local environments by specifying the skip_hosts property under asset_bundling.

asset_bundling: {
	skip_hosts: [""]

However, when the pages are generated with punch generate command, bundle helper will add the tag for the bundled file as expected.