Hello Laravel Friends,

In this blog, I will explain Compiling Assets (Mix) in Laravel 8.

What is Laravel Mix?

Laravel Mix is a package developed by Laracasts creator Jeffrey Way. It provides a fluent API for defining webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors.

In other words, Mix makes it compile and minify your application’s CSS and JavaScript files.

Installation & Setup

Before running Mix, you must first ensure that Node.js and NPM are installed on your machine:

Installing Laravel Mix

The only remaining step is to install Laravel Mix. Within a fresh installation of Laravel, you’ll find a package.json file in the root of your directory structure. The default package.json file already includes everything you need to start using Laravel Mix. 

Running Mix

The mix is a configuration layer on top of webpack, so to run your Mix tasks, you only need to execute one of the NPM scripts that are included in the default Laravel package.json file. When you run the dev or production scripts, all of your application’s CSS and JavaScript assets will be compiled and placed in your application’s public directory:

Watching Assets For Changes

The npm run watch command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change to one of these files:

Example for Compiling Assets (Mix) in Laravel 8:

Step 1: Take a fresh Laravel project, install all the prerequisites, and set up Laravel. For compiling assets, we install an npm using the npm install command.

Step 2: Now, create a js and stylesheet file in a location resources/js/app.js and resources/css/app.css for compiling.

Step 3: Then add the below code to your webpack.mix.js file.

Step 4: Then run the development build command to your root of the project.

Now you can check your public folder. 2 files are created: public/css/app.css and public/js/app.js.

js and css files

You can use this file asset in your blade file:

Conclusion:

This was all about Compiling Assets (Mix) in Laravel 8. If you have any questions, share them with me through the comment below. Check out more Laravel Tutorials and stay updated with us!

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]