1 year ago

Best practice for structuring app.js file

Posted 1 year ago by Digitalized

Hi all,

I have a question about best practice (or at least sensible practice) with regards to structuring an app.js file within Laravel.

In the past I included js files separately in my main template, each dealing with various parts of my application. However having recently watched one of Jeffrey's tutorials on Webpack, I am now looking to have a single app.js file for my project.

There are a fair few guides to using Webpack in Laravel, but I'm struggling to find some examples of the app.js file itself - with respect to a real-world project.

My webpack.mix.js file is currently configured like so:

let mix = require('laravel-mix');

], 'public/js/dist/app.js').version();

..and my app.js file in the src directory like this:

import Activities     from '../activities/activities.js';
import AddressFinder  from '../address/address-finder.js';
import ChartManager   from '../analytics/analytics.js';
import ImportUsers    from '../import/import-users.js';
import Confirm        from '../alerts/confirm.js';
import Toaster        from '../alerts/toaster.js';
import Modal          from '../alerts/modal.js';
import Api            from '../api/api.js';
import ChangeLanguage from '../language/change-language.js';

global.Activities     = Activities;
global.ChartManager   = ChartManager;
global.ImportUsers    = ImportUsers;
global.Confirm        = Confirm;
global.Toaster        = Toaster;
global.Modal          = Modal;
global.Api            = Api;
global.AddressFinder  = AddressFinder;
global.changeLanguage = new ChangeLanguage;

The public/js/dist/app.js file is the only file I include in my main view template;

In my src/app.js file I am importing any classes my views need to access globally, each of these main classes may include private classes from other files, as required.

In your experience, is this a good structure? Are there better ways of doing this?

One thing i'm not 100% sure about with this approach is how I can load scripts ad-hoc, for example, admin scripts shouldn't really be loaded by general users, etc.

I guess when everything is minified and packed this might not be so much of an issue, but it's something i'm wondering about, and whether I can add some conditional statements to fix this.

Thanks and look forward to hearing your advice, Paul

Please sign in or create an account to participate in this conversation.