Monday, March 6, 2017

Combining Multiple Files with Laravel Mix

I am currently in the process of diving into Laravel Mix and so far, whilst I fully understand what Laravel Mix is and how it works, I am trying to understand a little more about the common practices and 'How-Tos'...

For instance, consider this file structure:

/resources/assets/js/app.js (all global functions)
/resources/assets/js/index/index.js (functions specific to index.js)
/resources/assets/js/about/about.js (functions specific to about.js)
/resources/assets/js/contact/contact.js (functions specific to contact.js)

Now, ideally, I would like the following combined and minified in the following way:

/public/js/index/index-some_hash.js (including app.js)
/public/js/about/about-some_hash.js (including app.js)
/public/js/contact/contact-some_hash.js (including app.js)

As far as I understand, the way to achieve this is something like the following:

// Index
mix.js([
    'resources/assets/js/app.js',
    'resources/assets/js/index/index.js'
], 'public/js/index/index.js').version();

// About
mix.js([
    'resources/assets/js/app.js',
    'resources/assets/js/about/about.js'
], 'public/js/about/about.js').version();

// Contact
mix.js([
    'resources/assets/js/app.js',
    'resources/assets/js/contact/contact.js'
], 'public/js/contact/contact.js').version();

My Question

Quite simply, I would like to know if the above is the correct method for doing what I am trying to do? Are there better ways, or more common ways of achieving this?

If the above structure is wrong and there are other ways my files should be combined then please share your knowledge. However, unless there is a very good reason, I would like to avoid the following:

  • Serving two separate files for each page i.e. app.min.js and index.min.js. This requires two lookups per page, ideally it should be as few as possible
  • Serving the same file to ALL pages on my site. Serving code to a page that is not going to use it is a waste of resource, regardless of caching...

One Idea...

I noticed a line of code in one of the JS files; require('./bootstrap');. Call me old fashioned but I have never seen this in JavaScript (I assume it is from node.js). That said, obviously it is just loading the bootstrap.js file as a dependency into the specific file. So, with this in mind, would the following solution be better:

about.js

require('./app'); // Include global functions

// Do some magic here specifically for the 'about' page...

webpack.mix.js:

mix.js(['resources/assets/js/*/*.js'); // For all pages

If this is a better solution then how do I include files using SASS as well? Are there ways the above can be improved at all?



via Ben Carey

Advertisement