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:
node -v npm -v
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.
npm install
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:
// Run all Mix tasks… npm run dev // Run all Mix tasks and minify output… npm run prod
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:
npm run watch
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.
mix.js('resources/js/app.js', 'public/js') .postCss('resources/css/app.css', 'public/css', [ // ]);
Step 4: Then run the development build command to your root of the project.
npm run dev
Now you can check your public folder. 2 files are created: public/css/app.css and public/js/app.js.
You can use this file asset in your blade file:
<link href="{{ mix('/css/app.css') }}” crossorigin="anonymous"> <script src="{{ mix('/js/app.js') }}"></script>
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!