April 14, 2018 —John Koster
The mix
helper function can be used to generate URLs to a versioned Laravel Mix file. You should use this function when you reference assets compiled or minified using Laravel Mix; this is because Laravel Mix generates a hash as the name of the versioned file.
As of Laravel 5.4, the Laravel Elixir build system was renamed to Laravel Mix. If you are still using Laravel Elixir, you should refer to the elixir
helper function.
The signature of the mix
function is:
1function mix(2 $path,3 $manifestDirectory = ''4);
If we had had the following Mix configuration file:
1let mix = require('laravel-mix');2 3mix.js('resources/assets/js/app.js', 'public/js')4 .sass('resources/assets/sass/app.scss', 'public/css')5 .version();
We could create the following Blade template:
In resources/views/test.blade.php
:
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Example Blade Template</title> 5 6 <link rel="stylesheet" type="text/css" 7 href="{{ mix('css/app.css') }}"> 8</head> 9<body>10 11 <script type="text/javascript"12 src="{{ mix('js/app.js') }}"></script>13</body>14</html>
The final results would be similar to the following HTML:
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Example Blade Template</title> 5 6 <link rel="stylesheet" type="text/css" 7 href="/css/app.css?id=b9cb5c393f3dcc0fb457"> 8</head> 9<body>10 11<script type="text/javascript"12 src="/js/app.js?id=de5c280dd91bca2fadbf">13</script>14</body>15</html>
The Laravel Mix manifest directory can be changed by supplying a value for the $manifestDirectory
parameter. The manifest directory should contain the mix-manifest.json
file, which contains a mapping of the asset paths and the versioned path names. As an example, after executed the code samples in the previous example, the contents of the generated mix-manifest.json
file were:
1{2 "/js/app.js":3 "/js/app.js?id=de5c280dd91bca2fadbf",4 "/css/app.css":5 "/css/app.css?id=b9cb5c393f3dcc0fb457"6}
If the output directory of Laravel Mix has been changed, the new location can be specified using the $manifestDirectory
parameter:
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Example Blade Template</title> 5 6 <link rel="stylesheet" type="text/css" 7 href="{{ mix('css/app.css', 'ww3') }}"> 8</head> 9<body>10 11 <script type="text/javascript"12 src="{{ mix('js/app.js', 'ww3') }}">13 </script>14</body>15</html>
If the specified directory does not contain the mix-manifest.json
file an instance of Exception
will be thrown with the message "The Mix manifest does not exist.".
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.