Search code examples
csslaravelwebpacksasslaravel-mix

Laravel Mix import multiple globbed SCSS files into app.scss


I have a project structure where each component has its own SCSS file, and I would like to have all of these automatically imported into the project's main app.scss file, without having to list them all individually or update the list every time a new component is added. I know that merging a bunch of globbed CSS files could cause issues with selector order, but that is not a concern here.

I have tried this, with the components.scss file imported into app.scss:

mix.styles('resources/views/components/*.scss', 'resources/css/components.scss');
mix.sass('resources/css/app.scss', 'public/css');

And it basically works.

Except, mix.styles() runs after the Sass compilation, so you end up with the components.scss file from the previous execution being imported, rather than the current one.

Is there a way to solve this? Or is there another approach that would work?

As Sass @import does not support glob paths it's not possible to do something like this in app.scss as far as I am aware:

@import 'resources/views/components/*';

Solution

  • Discovered this can be done quite easily with node-sass-glob-importer, which is compatible with the Dart Sass implementation that Mix uses:

    const sassGlobImporter = require('node-sass-glob-importer');
    
    mix.sass('resources/css/app.scss', 'public/css', {
        sassOptions: {
            importer: sassGlobImporter(),
        }
    });
    

    resources/css/app.scss

    @import '../views/components/**/*.scss';