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:
1 2 3 |
<link href="{{ asset('css/example.css') }}" rel="stylesheet"> <script src="{{ asset('js/example.js') }}"></script> |
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:
1 |
npm install |
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):
1 2 3 4 5 |
// Execute Laravel Mix, but it doesn't minify the files. For test environment. npm run dev // Execute Laravel Mix and minfy all the files. Always for production. npm run production |
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.
1 |
npm run watch |
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:
1 2 3 |
mix .sass('resources/assets/sass/app.scss', 'public/css') ... |
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:
1 2 3 |
mix .less('resources/assets/less/app.less', 'public/css') ... |
And if it was a JS:
1 2 3 |
mix .js('resources/assets/js/app.js', 'public/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