in Laravel

Laravel Mix Extract And Versioning

When browsers load assets such as CSS and JS they will locally cache them so that they can served quicker the next time users visit the website.

The problem with this is that if you make future changes to the files and upload them to production some users may still be downloading the older version of the asset files.

A way around this is to add a querystring timestamp to the end of the asset URLs this will make sure that the browser downloads the latest version each time. But this may be overkill, you don't need users to download the files every time, they only need to be downloaded if something has changed.

Use Laravel mix you can do this will 2 simple methods. Mix extract and mix version.

Extract will allow you to take out third party libraries from your main JavaScript file allowing you to cache them for longer. For example if your application uses VueJS when you make a change to your JavaScript your users don't need to download VueJS again just your JavaScript file.

mix.js('resources/js/app.js', 'public/js')
   .extract(['vue']);

This will create 3 new files in your public/js folder

  • manifest.js
  • vendor.js
  • app.js

These need to be loaded on your page in a specific order

<script src="/js/manifest.js"></script>
<script src="/js/vendor.js"></script>
<script src="/js/app.js"></script>

Then we can add versioning to your JavaScript files by using the version method.

mix.js('resources/js/app.js', 'public/js')
   .extract(['vue'])
   .version();

The version method will create a unique hash to append to the files. As these are unique hashes you won't be able to reference this into your blade, so you'll need to use the mix function.

<script src="{{ mix('/js/manifest.js') }}"></script>
<script src="{{ mix('/js/vendor.js') }}"></script>
<script src="{{ mix('/js/app.js') }}"></script>

Subscribe To The Weekly Newsletter

Get weekly updates to your email