Laravel is one of the most popular PHP frameworks that provides various capabilities for rapid and straightforward web applications development. One of these capabilities is managing and bundling capabilities and frontend tools. Simply put, bundling means combining and optimizing CSS and JavaScript files into one or fewer files to enhance page load speed.
For bundling frontend resources in Laravel, it is usually used tools like Laravel Mix. Laravel Mix is a powerful package built on Webpack that allows you to easily manage your own resources through a straightforward process.
In this tutorial, we will together see how to bundle CSS and JavaScript resources using Laravel Mix. This process includes installing the necessary tool, relevant configurations, and the structure of the project.
The first time that you use Laravel Mix in your project, it might seem a bit complicated at first. However, after using it several times, you will quickly realize how much it saves time and energy.
Now, let's take a look at the necessary codes and then gradually explain how these codes work:
// webpack.mix.js file
let mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.version();
Code Explanation
let mix = require('laravel-mix');
This line imports Laravel Mix, allowing you to use it to bundle your own resources.
mix.js('resources/js/app.js', 'public/js')
This line specifies your main JavaScript file that is located at
resources/js/app.js
and bundles it in the public/js
directory.mix.sass('resources/sass/app.scss', 'public/css')
This line indicates the SASS file that is located at
resources/sass/app.scss
and bundles it in the public/css
directory..version()
This method adds a hash to the end of the output file name so that when the files are browsed, the user can download the most recent versions.