Optional Sass Import

Published 2 months ago by macmotp

I recently had to import optional files in SASS. Apparently there is no way to do it like so (that would be perfect):

@import optional_file !optional

or like in LESS

@import (optional) optional_file 

There is an issue on GitHub here -> https://github.com/sass/sass/issues/779 but it has not being solved, and maybe it will never be.

Do you know if there is a workaround, preferably not using js or webpack? Like "import if exists"?

Thank you

Best Answer (As Selected By macmotp)
vanderb

Ah ok. Just add the !default-flag to your variables in your variables.scss

$example-color: #fff !default;

So you can override the variables either before or after variables-import, because Sass looks for the default flag.

If there is no override the default-value used.

Thats the way, framework like bootstrap or foundation do.

Maybe here you can read more about that https://robots.thoughtbot.com/sass-default

vanderb

Just wrap your styles in the optional file as a sass mixin:

@mixin optional_file {
    .test { color: red }
    // other styles here
}

Then use the if-statement of sass to include the mixin

@import "optional_file";
@if $someval == true {
    @include optional_file;
}
macmotp

Thank you @vanderb for the answer. That would work but it doesn't help my case. I will be more specific: I have a Sass project with variables and other files depending on those variables:

// project/main.sass

@import variables.sass
// other files based on variables
// project/variables.sass
$example-color: #fff

But since it will be published through npm, I want that Laravel users could import the whole library - like for Bootstrap if you create a new Laravel project:

// /resources/sass/app.scss

@import ../node_modules/project/main.sass

This will work, but I want them to update the variables without extracting the whole library, so my goal is:

// project/main.sass

@import variables

// HERE IS WHAT I NEED:
@import (optional) ../../resources/sass/override.sass

// other files based on variables
// project/variables.sass
$example-color: #fff

And for user Laravel projects:

// /resources/sass/app.scss

@import ../node_modules/project/main.sass
@import override.sass
// /resources/sass/override.sass
$example-color: #000

In this way, users can override variables without braking anything on the library. I hope this can clarify

vanderb

Ah ok. Just add the !default-flag to your variables in your variables.scss

$example-color: #fff !default;

So you can override the variables either before or after variables-import, because Sass looks for the default flag.

If there is no override the default-value used.

Thats the way, framework like bootstrap or foundation do.

Maybe here you can read more about that https://robots.thoughtbot.com/sass-default

Please sign in or create an account to participate in this conversation.