How to Use Laravel Mix to Compile CSS and JavaScript?

Estimated read time 2 min read

Laravel Mix is a powerful tool for compiling and processing your CSS and JavaScript files in Laravel, a PHP framework. To use Laravel Mix to compile your CSS and JavaScript, you can follow these steps:

  1. Install Laravel Mix: Laravel Mix is included with a new Laravel project, so you don’t need to install it separately. You can verify that Laravel Mix is installed by checking the package.json file in your Laravel project.
  2. Create your CSS and JavaScript files: Create your CSS and JavaScript files in the resources folder of your Laravel project. You can use any CSS preprocessor like Sass or Less and any JavaScript framework like React or Vue.js.
  3. Configure Laravel Mix: In the root folder of your Laravel project, open the webpack.mix.js file. This file is used to configure Laravel Mix. You can add the following code to compile your CSS and JavaScript files:
const mix = require('laravel-mix');

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

In this example, Laravel Mix is configured to compile a resources/js/app.js JavaScript file and a resources/sass/app.scss Sass file into the public/js and public/css directories, respectively.

  1. Compile your CSS and JavaScript files: In the terminal, navigate to the root folder of your Laravel project and run the following command to compile your CSS and JavaScript files:
npm run dev

This will compile your CSS and JavaScript files and output them to the specified directories.

  1. Include the compiled files in your HTML: In your HTML file, include the compiled CSS and JavaScript files. You can do this by adding the following code to the head section of your HTML file:
<link rel="stylesheet" href="{{ mix('css/app.css') }}">

And by adding the following code to the body section of your HTML file:

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

That’s it! With these steps, you should be able to use Laravel Mix to compile your CSS and JavaScript files in your Laravel project.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply