Combining CSS and JavaScript files with Elixir

Possibly, the single most important step of the deployment process is to combine and minify CSS and JavaScript files. Minifying and combining five JavaScript files and three CSS files means that instead of eight HTTP requests, there will be only one. Also, by minifying the files by removing white space, line breaks, comments, and other techniques, such as shortening variable names, the file size will be reduced to a fraction of its original size. Despite the advantage, there are still many websites that continue to use unminified and uncombined CSS and JavaScript files.

Elixir provides a simple means to easily combine and minify files. The following code illustrates this example:

elixir(function(mix) {
    mix.scripts().styles();
});

The two methods, scripts() and styles(), will combine all of the JavaScript and CSS files into single files, all.js and all.css, respectively. By default, the two functions expect the files to be located at /resources/assets/js and /resources/assets/css.

When the gulp command has finished, the output will be like this:

[00:36:20] Using gulpfile /var/www/laravel.example/gulpfile.js
[00:36:20] Starting 'default'...
[00:36:20] Starting 'scripts'...
[00:36:20] Merging: resources/assets/js/**/*.js
[00:36:20] Finished 'default' after 246 ms
[00:36:20] Finished 'scripts' after 280 ms
[00:36:20] Starting 'styles'...
[00:36:20] Merging: resources/assets/css/**/*.css
[00:36:21] Finished 'styles' after 191 ms

Notice how the output conveniently states which directories were scanned. The contents are combined, referred to as merged in this context, but not minified. This is because, during development, debugging is too difficult on minified files. If only a certain file is to be merged, then the name of the file may be passed into the function as the first parameter:

mix.scripts('app.js'),

If multiple files are to be merged, then an array of filenames may be passed into the function as a first parameter:

mix.scripts(['app.js','lib.js']);

In a production environment, having minified files is desirable. To have Elixir minify both the CSS and JavaScript, add the --production option to the gulp command as follows:

$ gulp --production

This will produce the desired minified output. The default output directory is located at:

/public/js
/public/css
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset