In the previous tutorial, I showed you how you can use Laravel-Mix to compile your front end assets. In this post, I’ll show you how you can use Laravel Mix and a new Vapor package to compile, minify, and version your assets without breaking a sweat. …
As we saw in the previous tutorial, we have 3 npm run scripts at our disposal that we can use to compile our assets:
npm run webpack - to just compile the assets.
npm run dev - to continuously build the assets as you modify them.
npm run production - we didn’t cover this but this is what you’d use to compile your assets for production. Among few other things, the most important task it performs is minifying your assets.
As you know, browsers cache your assets to avoid downloading the same assets every time your load a page. But when you modify your assets, you want to force browsers to serve fresh copies. You can do this manually by adding a timestamp or a unique hash to your assets. If you use Laravel Mix, you can make it all automatic:
1: Open your
webpack.mix.js file and call
.version(). Your file should look like this:
2: Now from your terminal run:
You will now see that it generated few hashed files. You can now refer to these files from your .html/.leaf file as follows:
where xxxx and yyyy are hashes of corresponding files.
The thing is, as you change a file, its hash gets changed as well. So you have to remember to update all your asset references every time you make a change.
I know, it’s a pain to do that. What’s even worse is that because files are only versioned in production, when you are developing, you have to remember to change them back to non-versioned filenames.
To deal with this I’ve created a package called Vapor Mix. This package comes with a leaf tag that allows you to load hashed asset within your .leaf view files without referring to the hash of the file. The above scripts would look like this using Vapor Mix:
Don’t forget to bookmark this site and come back for more. If you want to say hi, I’m @ashokgelal on Twitter.