Autoloader for assets

Likewise Laravels autodiscovery for service providers, the Autoloader works by autodetecting JavaScript and CSS assets in a package and auto require those.

The concept is the same as Laravel, the autoloaded files are defined in composer.json but before it works, you must make a few changes in order for the script to run after every composer update.

Setup

Install the autoloader from Packagist:

composer require emilmoe/autoloader

It’s important that you load Vue from bootstrap.js. Laravel default will add it to app.js and must therefor be refactored. Add this after axios, and remove the load of Vue from app.js:

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue')

Add the following config to your WebPack settings (webpack.mix.js):

mix[..]
    .webpackConfig({
        output: {
            chunkFilename: 'js/[name].[chunkhash].js',
        }
    });
})

To enable Autoloader you must add it to your main composer.json file’s post update script as followed:

"post-install-cmd": [
    "EmilMoe\\Autoloader\\Autoloader::postInstall"
],
"post-update-cmd": [
    "EmilMoe\\Autoloader\\Autoloader::postUpdate"
]

And then run composer update to add autoloader configurations.

Package configuration

For a package to activate autoload, the scripts must be defined in it’s composer.json. It’s treated as a JavaScript file if it ends with js:

"extra": {
    "emilmoe": {
        "autoloader": [
            "vender/package/src/resources/sass/package",
            "vender/package/src/resources/js"
        ]
    }
}

Environment variables

In addition to autoloading scripts, Autoloader can prompt for values for new variables in the .env file and save the key value pair. Simply define which keys sould be populate typically with your package name first:

"extra": {
    "emilmoe": {
        "env": [
            "PACKAGE_VAR"
        ]
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *