npm install --save-dev laravel-mix-code-splitter
yarn add laravel-mix-code-splitter --save
Definition from google
1. webpack.mix.js
let mix = require('laravel-mix');
require('laravel-mix-code-splitter');
/** Normally, we create a single global file -- available on all pages **/
mix.js('resources/js/app.js', 'public/js/app.js')
/*----------------------------------------------------------
| Code splitting allows us to "split" our code up.
*----------------------------------------------------------
|
| -> resources
| . /js/split/home.js
| . /js/split/badges.js
| . /js/split/invoices.js
|
*/
.split(mix.js, 'resources/js/split', 'public/js/split')
/*----------------------------------------------------------------------------
| Providing splits of our code for each page or feature specific page
*----------------------------------------------------------------------------
|
| -> public
| . /js/split/home.js
| . /js/split/badges.js
| . /js/split/invoices.js
|
*/
After mix does its thing, there's multitudes of ways to dynamically load the proper split for the current route ~ here's a simpler implementation I personally like
routes/web.php
Add names to your routes, we'll use resourceful routes to speed the example up
Route::resource('home', 'HomeController')->home('home');
Route::resource('badges', 'BadgesController')->name('badges');
Route::resource('invoices', 'InvoiceController')->name('invoices');
Add snippet to your primary layout blade file
resources/views/layouts/app.blade.php
<script src="https://github.com/zhorton34/laravel-mix-code-splitter/raw/master/{{ asset('js/app.js') }}"></script>
@if (asset( "js/split". Str::of(Route::currentRouteName())->before('.')->append('.js') ))
<script src="https://github.com/zhorton34/laravel-mix-code-splitter/raw/master/{{ asset( Str::of(Route::currentRouteName())->before('.')->start('js/split')->finish('.js') ) }}"></script>
@endif
home.js loads on visits to
badges.js loads on visits to
invoices.js loads on visits to
app.js loads on every page
let mix = require('laravel-mix');
require('laravel-mix-code-splitter');
mix
.js('resources/js/app.js', 'public/js/app.js')
.split(mix.js, 'resources/js/split', 'public/js/split')
.css('resources/js/app.css', 'public/css/app.css')
.split(mix.css, 'resources/css/split', 'public/css/split')
.css('resources/js/app.css', 'public/css/app.css')
.split(mix.css, 'resources/css/split', 'public/css/split')
.postCss('resources/css/main.css', 'public/css', [require('precss')()])
.split(mix.postCss, 'resources/css', 'public/css/split', [require('precss')()])
// etc...