@import in @if statement in Sass

woutvdd picture woutvdd · Dec 14, 2012 · Viewed 28.5k times · Source

I want to load only the css needed for the login page for performance. On my other pages I want a grouped css file that will be cached on every page which contain all my css.

I have the following files:

minifiedcssforloginpage.scss
grouped-pages.scss

In minifiedcssforloginpage.scss I declare $load-complete-css:false. Afterwards I import myproject.scss which contains all the imports of my modules, layouts, core... In myproject.scss i want to do something like

@if $load-complete-css {
     @import module1;
     @import module2;
     @import module3;
}

So minifiedcssforloginpage.scss would generate minifiedcssforloginpage.css with less css then grouped-pages.css (that has a var $load-complete-css set to true).

But I get an error that this is not possible "Import directives may not be used within control directives or mixins".

Answer

cimmanon picture cimmanon · Dec 14, 2012

It's one of those things that's just not allowed. The only thing you can do is turn those imports into mixins (import the file outside the @if and call the mixin where appropriate).

Clarification:

_partial.scss

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

styles.scss

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