I have a number of Laravel projects which use Webpack and ES5 Modules to create/provide separate JS files which can be imported only as and when required by a page. Some of my projects are quite complex and pages need their own specific javascript. These projects are not built using responsive engines like Vue, React or Livewire (although that is something I've moved towards more recently, preferring TALL stack solutions).
I use Webpack Mixins to add my separate JS files, following the naming convention of js/pages/[some page name here]/[some module name here].js:
mix.js('resources/js/app.js', 'public/js')
.js('resources/js/pages/some-page/some-module.js', 'public/js/pages/some-page/')
Each Laravel blade page includes a small JS script which holds an array of all the required JS pages that need to be used on that page (along with any global shared helper functions). Normally this is just one JS page, but more can be added.
document.js_arr = [
{
"file" : "pages/some-page/some-module.js", //removed "js/" to make the reference smaller
"shared" : "validateEmail,dateFormatting", //two sample global function references I might need importing in to my local js file.
}
];
After the webpage has loaded, my app.js checks for any requested JS import (using webpackChunkName and the [name] placeholder), imports it and handles any shared functionality requirements:
if( undefined != document.js_arr){
document.js_arr.forEach((js_object) => {
import(
/* webpackChunkName: "js/[name]" */
/* webpackMode: 'eager' */
'./'+js_object["file"]
)
.then( module => {
if(js_object["shared"]){
let shared_objects = js_object["shared"].split(',');
let objects = [];
shared_objects.forEach((shared_object) => {
if( eval(shared_object) ){
objects.push( eval(shared_object) );
}
});
if(objects.length > 0){
//Bind our local references to global shared functions
module.shareGlobalFunctions(...objects);
}
}
module.default();
} )
.catch(error => { console.log( error ); } );
} );
}
The solution I have actually works well enough. But more recent versions of Laravel suggest using Vite instead of Webpack. I'm not as clued up with Vite. How would I go about setting up the same system to work with Vite? Are there similar processes as ChunkNames and placeholder references like [name] in Vite?