Getting started with Laravel Mix for frontend development
You will need Laravel 5.6+ and Node 8.10+ installed on your machine.
In this tutorial, we will look at how to set up Laravel Mix to compile SCSS, LESS or plain CSS for your application.
Laravel Mix is a tool for compiling and optimizing assets in a Laravel app. It’s similar to a build tool like gulp, Grunt and such like. it’s specific to Laravel but can also be used externally as an npm package. Laravel Mix covered 80% of Webpack’s use case to make compiling assets easier. In a nutshell, Laravel Mix compiles, minifies and stores your assets in your application’s public folder for easy reference.
Prerequisites
This tutorial assumes you have a basic understanding of Laravel v 5.6+ and since Laravel Mix is an npm package a little familiarity with npm will help. However, it is not required.
You will need to have Node v 8.10 + and npm v 5+ installed on your system. If you don’t you can install it by following this guide.
Getting started
To use Laravel Mix, we need to have a Laravel app installed. If you don’t already have one setup, you can set up one by following this installation guide. After installation your directory should look like this:
├── app
│ ├── Console
│ │ └── Kernel.php
│ ├── Exceptions
│ │ └── Handler.php
│ ├── Http
│ │ ├── Controllers
│ │ │ ├── Auth
│ │ │ │ ├── ForgotPasswordController.php
│ │ │ │ ├── LoginController.php
│ │ │ │ ├── RegisterController.php
│ │ │ │ ├── ResetPasswordController.php
│ │ │ │ └── VerificationController.php
│ │ │ └── Controller.php
│ │ ├── Kernel.php
│ │ └── Middleware
│ │ ├── Authenticate.php
│ │ ├── CheckForMaintenanceMode.php
│ │ ├── EncryptCookies.php
│ │ ├── RedirectIfAuthenticated.php
│ │ ├── TrimStrings.php
│ │ ├── TrustProxies.php
│ │ └── VerifyCsrfToken.php
│ ├── Providers
│ │ ├── AppServiceProvider.php
│ │ ├── AuthServiceProvider.php
│ │ ├── BroadcastServiceProvider.php
│ │ ├── EventServiceProvider.php
│ │ └── RouteServiceProvider.php
│ └── User.php
├── artisan
├── bootstrap
│ ├── app.php
│ └── cache
│ ├── packages.php
│ └── services.php
├── composer.json
├── composer.lock
├── config
│ ├── app.php
│ ├── auth.php
│ ├── broadcasting.php
│ ├── cache.php
│ ├── database.php
│ ├── filesystems.php
│ ├── hashing.php
│ ├── logging.php
│ ├── mail.php
│ ├── queue.php
│ ├── services.php
│ ├── session.php
│ └── view.php
├── database
│ ├── factories
│ │ └── UserFactory.php
│ ├── migrations
│ │ ├── 2014_10_12_000000_create_users_table.php
│ │ └── 2014_10_12_100000_create_password_resets_table.php
│ └── seeds
│ └── DatabaseSeeder.php
├── package.json
├── phpunit.xml
├── public
│ ├── css
│ │ └── app.css
│ ├── favicon.ico
│ ├── index.php
│ ├── js
│ │ └── app.js
│ ├── robots.txt
│ └── svg
│ ├── 403.svg
│ ├── 404.svg
│ ├── 500.svg
│ └── 503.svg
├── resources
│ ├── js
│ │ ├── app.js
│ │ ├── bootstrap.js
│ │ └── components
│ │ └── ExampleComponent.vue
│ ├── lang
│ │ └── en
│ │ ├── auth.php
│ │ ├── pagination.php
│ │ ├── passwords.php
│ │ └── validation.php
│ ├── sass
│ │ ├── app.scss
│ │ └── _variables.scss
│ └── views
│ └── welcome.blade.php
├── routes
│ ├── api.php
│ ├── channels.php
│ ├── console.php
│ └── web.php
├── server.php
├── storage
│ ├── app
│ │ └── public
│ ├── framework
│ │ ├── cache
│ │ │ └── data
│ │ ├── sessions
│ │ ├── testing
│ │ └── views
│ └── logs
├── tests
│ ├── CreatesApplication.php
│ ├── Feature
│ │ └── ExampleTest.php
│ ├── TestCase.php
│ └── Unit
│ └── ExampleTest.php
├── webpack.mix.js
└── yarn-error.log
After installing Laravel you need to install your Node dependencies (because Laravel Mix comes pre-packed as a node dependency). In your terminal type:
npm install
Now see this in your terminal:
Exploring the directory
After installation, a node_modules
folder will be added to your project’s directory. But for our purposes, we’ll be concerned with the resources
folder and the webpack.mix.js
file in the project root which is where Laravel Mix does all its magic.
Under the resources
folder you will see the following folders:
├── js
│ ├── app.js
│ ├── bootstrap.js
│ └── components
│ └── ExampleComponent.vue
├── lang
│ └── en
│ ├── auth.php
│ ├── pagination.php
│ ├── passwords.php
│ └── validation.php
├── sass
│ ├── app.scss
│ └── _variables.scss
└── views
└── welcome.blade.php
The job of Laravel Mix is to compile all these assets and save them in the public directory to be used and accessed by the world. To see that in action, in your terminal type:
npm run dev
When it’s finished, you will see this in your terminal:
Now if you look in the css and js
folder in your public directory, you’d see it has been updated with the compiled code below:
// app.css
/* Copyright 2011-2018 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
:root {
--blue: #3490dc;
--indigo: #6574cd;
--purple: #9561e2;
--pink: #f66D9b;
--red: #e3342f;
--orange: #f6993f;
--yellow: #ffed4a;
--green: #38c172;
--teal: #4dc0b5;
--cyan: #6cb2eb;
--white: #fff;
--gray: #6c757d;
--gray-dark: #343a40;
--primary: #3490dc;
--secondary: #6c757d;
--success: #38c172;
--info: #6cb2eb;
--warning: #ffed4a;
--danger: #e3342f;
--light: #f8f9fa;
--dark: #343a40;
--breakpoint-xs: 0;
--breakpoint-sm: 576px;
--breakpoint-md: 768px;
--breakpoint-lg: 992px;
//app.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
One of the good things about Laravel Mix is the ability to compress or minify files and make the production ready. To see a list of commands possible, we can run this code on your terminal:
npm run dev
: this compiles the assets down to the public directory
npm run watch
: this compiles the assets to the public directory but also watches for new changes and auto updates.
npm run prod
: this compiles and minifies the assets to the public directory.
Let’s see how these various commands work.
First, let’s minify the code using npm run prod
. In your terminal type npm run prod
.
Once that’s done in your terminal you should see this:
Now check your CSS js
folder in the public directory you’d see the code has been minified to one line like:
// app.css
@import url(https://fonts.googleapis.com/css?family=Nunito);/*!
* Bootstrap v4.1.3 (https://getbootstrap.com/)
* Copyright 2011-2018 The Bootstrap Authors
* Copyright 2011-2018 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/:root{--blue:#3490dc;--indigo:#6574cd;--purple:#9561e2;--pink:#f66d9b;--red:#e3342f;--orange:#f6993f;--yellow:#ffed4a;
// app.js
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};
Next lets auto update the code using npm run watch
. In your terminal type npm run watch
.
Once that’s done in your terminal you should see this:
To see this in action let’s add code to our scss
file in our resources/sass
directory. Open the app.scss
file and add the following lines of code to it.
.content {
width: 600px;
margin: 0 auto;
font-size: 20px;
margin-top: 50px;
p {
color: yellow;
}
}
Once you save if you check your terminal you’d notice it auto-compiled with you typing any npm
commands.
Although it happens quick, you can always confirm by looking at the time difference of the last compilation.
To see the result of our code live in action we need to reference the CSS file in our Laravel homepage in resources/views/welcome.blade.php
In the file’s head let’s link to out css by adding this line of code to it.
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
Now update the HTML on the page to the following lines:
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div class="content">
<p> Getting Started with Laravel Mix </p>
</div>
</body>
</html>
Now start your server by typing: php artisan serve
in your terminal. In your browser you should see this:
Finally, let’s explore the Laravel Mix config file. In your root directory open the webpack.mix.js
file. You will see the following lines of code:
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
As you can see in the comment it says By default, we are compiling the Sass
| file for the application and bundling up all the JS files.
By default, Laravel assumes you will use sass
for your development. However, other methods exist depending on your choice of language.
For less
Laravel Mix has a less function you can use to compile your less assets. The syntax looks like:
mix.less('resources/less/app.less', 'public/css');
Basically, this means compile all the assets in the app.less
in that directory and save it under the public/css
directory. Less also supports method chaining to compile multiple files assuming you had over one file like so:
mix.less('resources/less/app.less', 'public/css')
.less('resources/less/admin.less', 'public/css');
You can also use mix with to compile all your plain CSS files into one huge file to reduce the number of calls your browser makes to fetch the files from the server:
mix.styles([
'public/css/vendor/normalize.css',
'public/css/vendor/videojs.css'
], 'public/css/all.css');
Conclusion
In this tutorial, we have seen how to work with Laravel Mix in our applications to make asset compilation a breeze. This tutorial is merely an introduction, to learn more about Laravel Mix visit the official docs page or the visit the Laravel Mix website. If you would like to play around with the code for this tutorial, it is hosted in this public GitHub repository. Thanks for reading! Happy Development!
26 February 2019
by Samuel Ogundipe