
AdonisJS: Using Laravel Mix's mix Function
I come from a Laravel background, so when I started developing a project with AdonisJS, I missed one of Laravel’s most useful front-end tools: Laravel Mix.
What I missed was Laravel Mix’s mix function. It lets you use hashed asset filenames. If you always serve assets from the server with the same filename, the browser may serve an older cached version. Caching can improve your site’s speed, but you still need to serve the latest version of each asset. To avoid this, developers can add a hash or create a function from scratch. However, if Laravel already provides the function, why not use the same logic in AdonisJS?
The goal is to create a global function for views. Add it to start/hooks.js.
const { hooks } = require("@adonisjs/ignitor");// Import the mix manifest fileconst manifest = require("../public/mix-manifest");
hooks.after.providersBooted(() => { const View = use("View");
// Register the mix function in Edge views View.global("mix", function (asset) { if (!manifest[`/${asset}`]) { return "404-asset-not-found"; }
return manifest[`/${asset}`]; });});Then restart your AdonisJS server. You can use the function in your views in two ways: with AdonisJS helpers or HTML.
{{ css(mix('css/your-styles.css')) }}
<!-- or --><link href="{{ mix('css/your-styles.css') }}" rel="stylesheet" />