Jan30th,19 place your img

Laravel Mix in a non-Laravel project with Twig Support

Recently, whilst working on the new Playlist-Converter front-end, I needed a fast and easy solution compile the assets (Compile the Sass files, minify the js code for production …etc). However, since I was using Twig’s templating engine I also needed a solution that can be integrated with it.

The first thing that I thought of was:

Do it like Laravel does it…

After a few google searches, I found this: Laravel Mix, formerly Elixir, which is a PHP API wrapper for Webpack used by Laravel to make asset compiling incredibly easy.

The problem is now: how can I use it in a non-Laravel project? Well, here’s how I accomplished that.

Initial setup

First of all, If you don’t already have one defined, initialize an NPM project. You will need to have Node and NPM installed globally for this.

cd ProjectFolder/
 npm init -y
 npm i laravel-mix --save-dev
 cp -r node_modules/laravel-mix/setup/** ./

That should then give you

  • node_modules/ (Don’t forget to add this to your .gitignore if you’re using Git for VCS)
  • package.json
  • webpack.config.js
  • webpack.mix.js

Next, you need to configure some NPM actual build scripts, instructions for that (and more) can be found on the Github install options for Mix.

Adding Twig Support

Now if we’re going to use Laravel-mix’s cache busting solution (which adds a hash to compiled asset to force the browser to update cache, so app.js might turn into app.b2328beb0372c051d06d.js. ) We need a way to fetch the newly generated asset name and add it to our HTML.

I tried to lookup some already made Twig extensions, which lead me to this repo: Elixir-twig-extension.

However, it wasn’t updated since Dec 6, 2016. So, using the magic of Github fork, I re-wrote my own extension and called it … wait for it .. Laravel-Mix Twig Extension.

Installing the extension

You can simply use Composer:

composer require stormiix/laravel-mix-twig-extension:dev-master


Register the extension

use Stormiix\Twig\Extension\MixExtension;

$mix = new MixExtension(
$publicDir, // the absolute public directory
$manifestName // the manifest filename (default value is 'mix-manifest.json')

Using the Extension

<link rel="stylesheet" href="{{ Mix('css/all.css') }}"> 
<script src="{{ Mix('js/all.js') }}"></script>


Although I'm not actively looking for job opportunities, my inbox is still open for you.
Feel free to ask me anything! place img