πŸŽ‰ New release for Pusher Chatkit - Webhooks! Extend your in-app chat functionality
Hide
Products
chatkit_full-logo

Extensible API for in-app chat

channels_full-logo

Build scalable realtime features

beams_full-logo

Programmatic push notifications

Developers

Docs

Read the docs to learn how to use our products

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Sign in
Sign up

Getting started with Laravel Mix for frontend development

  • Samuel Ogundipe
February 26th, 2019
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!

Clone the project repository
  • JavaScript
  • Laravel
  • PHP
  • no pusher tech

Products

  • Channels
  • Chatkit
  • Beams

Β© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.