Table of contents

Nwidart Laravel Modules Assets to Public using Laravel Mix

In this post, if you are using Nwidart Laravel Modules for your Laravel Project and you want to combine the modules assets to the public into one using Laravel mix. Then this is for you before I did this post I got a problem also on how to do it until I found a solution and I modified it that suitable for my needs. In your webpack.mix.js file inside your Laravel Project you will see their default code:

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

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

 

As you can see the code only read the resources folder so I modified the code to read dynamically every modules js and sass file and here is the final code below:

const mix = require('laravel-mix');
const fs = require('fs');
const path = require('path');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

const moduleFolder = './Modules';

const dirs = p => fs.readdirSync(p).filter(f => fs.statSync(path.resolve(p,f)).isDirectory());

// Get the available modules return as array
let modules = dirs(moduleFolder);

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/scss/app.scss', 'public/css');

// Loop available modules
modules.forEach(function(mod){
   mix.js(__dirname  + "/Modules/" + mod + "/Resources/assets/js/app.js", 'public/js');
   mix.sass(__dirname  + "/Modules/" + mod + "/Resources/assets/sass/app.scss", 'public/css');
});

// Let's parse again to fix the newline every module for css
mix.styles(['public/css/app.css'], 'public/css/app.css');

 

So if your webpack.mix.js file has a default code then just replace it with the code above. I hope it helps. Happy coding :)