Laravel 5.4 #12 : Assets and Laravel Mix

We have been talking a little bit about everything, even to certain things we can give them the design we want, but we have not explained how these JS and CSS files are included. Today we will explain how to do it and also explain a tool that has Laravel called Laravel Mix.

Laravel Mix is a tool that allows us to compile and minify our assets (supports CSS and JS preprocessors) very easily.

Include CSS and JavaScript

To include CSS and JS files, you can put them directly in the  public/css or  public/js directory and then link them from the layout with the asset() function:

So they would be added and we could add the code in these files.

 

Laravel Mix

Laravel Mix is a tool that Laravel includes based on Webpack.js that allow us to minify and compile our assets easily.

First of all, we need to have Node.js installed, you can download it from here.

Once installed, we will have to go to the root of the project and execute the following command from the command line, to install the packages that are in the file package.json . They will be necessary to be able to use Laravel Mix:

When it finishes, we can execute Laravel Mix. To execute it, we will have to execute one of this commands (depending on the environment in which we are):

We can also use the following command that allows us to modify the file while automatically recompile the file every time we save. Because in the other way, we would have to execute the compilation command every time we change something in the file.

To indicate which files we want to compile, we must go to the webpack.mix.js  file. There you add both JS files and CSS preprocessors, as well as normal CSS, all files are added there. You can find more info in the documentation.

For example, if we use Sass as pre-processor we would have to add this line:

We indicate the path where the original file is and the path where we want it to be saved once compiled.

Or this line if we use Less:

And if it was a JS:

 

If you want to know more about Laravel Mix and all its features, check out the documentation.

-

– Laravel Mix: https://laravel.com/docs/5.4/mix