How to Run Gulp Tasks in Laravel with Elixir

This tutorial describes how to use laravel’s elixir to run Gulp tasks. Gulp is a javascript task runner, it keeps things simple and makes the complex task manageable.

Here I am gonna show you how easy it is to use Gulp with Laravel’s Elixir to combine and minify application CSS and JavaScript files.

Node installation

Before using Gulp, make sure you have Node.js installed . To install Node.js click here .To check that Node.js is installed on your system, run the following command and it will show the current version of Node.js installed on your system.

How to Run Gulp Tasks in Laravel with Elixir

Gulp installation

Now install Gulp with following command. Gulp will be used to run all your elixir tasks.

--global parameter indicates that, we are installing Gulp globally.

Assets Compilation

To use the elixir, from the root of your Laravel application run the command. Once you are done with assets compilation, you will see a file gulpfile.js in your project’s root. In this file, we will define all the Gulp tasks that we need to perform.

Above command will download all the elixir(node) dependencies which were mentioned in package.json file. package.json is just like composer.json file in your project, which is used to define all the PHP dependencies in your project.

How to Combine CSS and JavaScript

For example if you want to combine two css files called app.css and main.css into a single file all.css, then open your gulpfile.js file, add following task

Note that css files to be combined are stored in public/assets/css directory and combined, minified files will be stored in the public/css directory. Similarly you can combine JS file.

In case of JS files you need to use mix.scripts() function instead of mix.styles() and your JS files should be present in resources/assets/js directory.

Versioning CSS and JavaScript

This will create css,js files and store it with a unique hashed name like all-d782e68f.css in public/build/css directory.Same applies for JavaScript also.

Now, if you are thinking that you will have to change the CSS file in your project every time you version it, then do not worry. It is very simple, just use the elixir() helper function to pull the correct hashed file as shown below.

This will return the correct version of your CSS file.

Execute elixir tasks

Now you know how you can create Elixir tasks to combine your CSS or JavaScript file. You need to execute them in order to see combined assets. Run the following command

If you also want to minify your converted CSS and JS file then run gulp with production option.

Instead of running gulp every time you make a change you can just run

Sometimes you might just want to run a single task and for style compilation run

for compilation of coffeescript files

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.