Laravel Mix is a fluent JavaScript API for defining Webpack build steps for your Laravel application. It's a wrapper around Webpack that simplifies the configuration and provides a clean and expressive syntax for defining asset compilation and bundling tasks. Here's a step-by-step guide on how to implement Laravel Mix:
Make sure you have Node.js and NPM installed on your system. Laravel Mix requires these tools. Then, navigate to your Laravel project directory in the terminal and run:
bashnpm install
This command installs the necessary dependencies, including Laravel Mix.
Open the webpack.mix.js
file in the root of your Laravel project. This file is used to configure the Mix build process. Here's a basic example:
javascriptconst mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
In this example, we are compiling the app.js
file from resources/js/
to public/js/
and the app.scss
file from resources/sass/
to public/css/
.
To compile your assets, run the following command in the terminal:
bashnpm run dev
If you're in a development environment and want to enable hot module replacement, use:
bashnpm run hot
Watch for Changes:
If you want Mix to watch for changes and automatically recompile assets during development, use the watch
command:
bashnpm run watch
Production Builds:
For production, use the prod
command to minify and optimize your assets:
bashnpm run prod
Versioning:
Mix automatically versions your assets to bust caches. Use the mix
helper function in your Blade templates to include the versioned assets:
html<link rel="stylesheet" href="{{ mix('css/app.css') }}">
<script src="{{ mix('js/app.js') }}"></script>
Customizing Configuration:
You can customize the Mix configuration by chaining additional methods in your webpack.mix.js
file. Refer to the official documentation for more options.
BrowserSync: Laravel Mix includes BrowserSync for live reloading. Run the following command to proxy your app through BrowserSync:
bashnpm run watch-poll
This is especially useful if you're working on a virtual machine.