Laravel Mix – The Complete Guide

Laravel Mix The Complete Guide

Laravel provides a fluent utility to compile all your frontend assets like stylesheets and scripts called Laravel Mix. In this post, we will find out what is Laravel Mix and how we can use it.

What is Laravel Mix?

According to Laravel’s Offical Documentation:

Laravel Mix provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors.

If you have ever tried to use WebPack for assets compilation, you will find out how easy it is with Mix to compile all your assets. You define assets compilation with a single line and it’s preconfigured settings will do the job for you.

In the webpack.mix.js file we will manage all our assets which need to be compiled. You can find this file at the root of the Laravel application.

Installing Laravel Mix

To install Mix in your Laravel application, you will need to have NodeJS installed on you machine.

If you have already set up the NodeJs than you can go ahead and start with Mix setup.

If not, then you have to download NodeJs Setup file and install it just like other software on your system. After running the successful installation, you can run below commands to check if the Node is installed and also check the version installed on your machine.

// Node Version
node -v // v8.12.0

// NPM version
npm -v // 6.9.0

NodeJS is a open source server environment and NPM (Node Package Manager) is a dependency management utility to manage Node modules just like Composer for PHP. I will write a complete article on NodeJS and NPM in the future.

After you have installed NodeJS, run below command to install the required modules for NodeJS.

npm install

This command will take some time, as it will install all modules required by NodeJS in a node_modules folder. In the root of Laravel application, you will also find a file package.json, this file contains all the settings and dependency packages. You can change the dependency packages as per your requirement. All dependencies added by Laravel by default in packages.json file will look like below.

"devDependencies": {
    "axios": "^0.18",
    "bootstrap": "^4.0.0",
    "cross-env": "^5.1",
    "jquery": "^3.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.5",
    "popper.js": "^1.12",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.15.2",
    "sass-loader": "^7.1.0",
    "vue": "^2.5.17"
}

Running Mix and Watching Assets

After successfully running npm install command, now you can run the Mix and start compiling your assets. Executing tasks in Mix is very easy, run one of the below commands to compile your assets.

// Run all Mix tasks
npm run dev

// Run all Mix tasks and minify them for the production

npm run production

You can also watch the changes while you are editing assets file. Run below command and watch all changes. Webpack only watches files, which are mentioned in webpack.mix.js file.

npm run watch

Working with Stylesheets

As we know now, how to compile assets in Mix, let’s explore what we can achieve using Mix.

Laravel Mix provides full support for most common CSS pre-processors like SASS, LESS, and Stylus. You can easily manage them in Mix.

Less

The less() method is used to compile all less files into a CSS file like below.

mix.less('resources/less/style.less', 'public/css');

// Multiple less files
mix.less('resources/less/style.less', 'public/css');
   .less('resources/less/app.less', 'public/css');

// Compile and save with new name
mix.less('resources/less/style.less', 'public/stylesheets/style.css');

SASS

The sass() method is used to compile sass files into a CSS file.

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

// Multiple sass files
mix.sass('resources/sass/style.scss', 'public/css');
   .sass('resources/sass/app.scss', 'public/css');

// Custom filename
mix.sass('resources/sass/style.scss', 'public/css/app.css');

Plain CSS Stylesheets

You can concatenate plain CSS files into one file, using the styles() method like below.

mix.styles([
    'public/css/vendor/bootstrap.css',
    'public/css/vendor/animate.css'
], 'public/css/all.css');

Working with JavaScript

The mix can compile your latest version of JavaScript code like ECMAScript 2015 (and so on…) into a single JavaScript file. You can use the js() method to compile JavaScript code.

mix.js('resoureces/app.js', 'public/js');

With an above single line of code, you can compile ECMAScript 2015 syntax, compilation of vue files, compilation of modules and minification for the production environment.

You can also combine multiple JavaScript files into a single file using the scripts() method.

mix.scripts([
    'public/js/admin.js',
    'public/js/dashboard.js'
], 'public/js/all.js');

Copying Files & Directories

The copy() method can be used to move files and directories from one location to another. You can use this method if you want to move some fonts files from the node_modules folder to another location.

mix.copy('node_modules/font-awesome/fonts/*', 'public/fonts/');

When you copy a directory using copy() method, it will flatten the directory structure. To maintain the directory structure simply use copyDirectory() method.

mix.copyDirectory('resources/img', 'public/img');

Versioning

The version() method will automatically add the unique hash to the filename when we compile our assets.

mix.js('resources/js/style.js', 'public/js').version();

BrowserSync Reloading

BrowserSync is automatically monitoring all files for new changes, and update changes to the browser. Using BrowserSync you don’t have to refresh your browser manually. You can use the browserSync() method to define this task.

// You need to call the given method to add the support.
mix.browserSync('app.dev');

You need to add a string (proxy) or object (BrowserSync settings) to this method. After that, you can run the npm run watch command. Now, when we modify our files, browser sync instantly refreshes the page to reflect your changes.

Laravel Mix Methods

There are several more Mix methods which you can not find in the webpack.mix.js file. Here is the list of all available methods by Mix:

// Laravel Mix Methods
// mix.js(src, output);
// mix.react(src, output); <-- Identical to mix.js(), but registers React Babel compilation.
// mix.extract(vendorLibs);
// mix.sass(src, output);
// mix.standaloneSass('src', output); <-- Faster, but isolated from Webpack.
// mix.fastSass('src', output); <-- Alias for mix.standaloneSass().
// mix.less(src, output);
// mix.stylus(src, output);
// mix.postCss(src, output, [require('postcss-some-plugin')()]);
// mix.browserSync('my-site.dev');
// mix.combine(files, destination);
// mix.babel(files, destination); <-- Identical to mix.combine(), but also includes Babel compilation.
// mix.copy(from, to);
// mix.copyDirectory(fromDir, toDir);
// mix.minify(file);
// mix.sourceMaps(); // Enable sourcemaps
// mix.version(); // Enable versioning.
// mix.disableNotifications();
// mix.setPublicPath('path/to/public');
// mix.setResourceRoot('prefix/for/resource/locators');
// mix.autoload({}); <-- Will be passed to Webpack's ProvidePlugin.
// mix.webpackConfig({}); <-- Override webpack.config.js, without editing the file directly.
// mix.then(function () {}) <-- Will be triggered each time Webpack finishes building.
// mix.options({
//   extractVueStyles: false, // Extract .vue component styling to file, rather than inline.
//   processCssUrls: true, // Process/optimize relative stylesheet url()'s. Set to false, if you don't want them touched.
//   purifyCss: false, // Remove unused CSS selectors.
//   uglify: {}, // Uglify-specific options. https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
//   postCss: [] // Post-CSS options: https://github.com/postcss/postcss/blob/master/docs/plugins.md
// });

Conclusion

I personally recommend you to read the complete documentation of Laravel Mix. If you have any question or suggestion regarding Laravel Mix, let us know in the comment box below.

Your little help will keep this site alive and help us to produce quality content for you.