Home / Snippets / Laravel Mix Assets Cache Busting
Laravel Mix Assets Cache Busting cover

Laravel Mix Assets Cache Busting

496

3 years ago

0 comments

To enable Laravel assets cache busting for production you can set call the "version()" method from within your "webpack.mix.js". By making use of cache-busting your assets can be cached indefinitely and only when you deploy new changes to your assets, the new one will take effect. How this work behind the scene is that Laravel compiles the assets with a timestamp and unique token to force the browser to load fresh assets instead of serving the copies of the old code.

Define Version Method
To define the version method only on production you can make use of the "inProduction()" check.
# webpack.mix.js

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js');

if (mix.inProduction()) {
    mix.version();
}

Run Production Command
Once you have defined the "versions()" method like above, that you need to run the "prod" command.
npm run prod

# or if you are using yarn
yarn prod

Use mix() on Laravel Blade
Then specify the assets on the blade file by calling the "mix()" function.
# for styling
<link rel="stylesheet" href="{{ mix('css/app.css') }}">

# for javascript
<script src="{{ mix('/js/app.js') }}"></script>

Full code example for the blade file available below.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="{{ mix('js/determine-theme.js') }}" defer></script>
    <link rel="stylesheet" href="{{ mix('css/app.css') }}">

</head>
<body>
    <!-- your other codes here -->

    <script src="{{ mix('js/app.js') }}" defer></script>
</body>
</html>
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this