@import in @if statement in Sass

34,859

Solution 1

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;
}

Solution 2

The core dev team is reluctant to implement this feature, although they are considering the implementation of a brand new dependency system.


See the following Github issues :

Solution 3

Put your styles into various partial files in a way that makes sense to you. Then, you can have create a separate SASS file for your login page that imports only the files with the relevant styles.

To quote from my answer to another question:

It is currently not possible to use SASS to include files dynamically. @import cannot be used within control directives (e.g. @if) or mixins, using a variable in an import directive is erroneous syntax, and there is no directive for ending file execution early (which effectively would allow conditional imports). However, you can solve your issue by changing how you structure your style rules.

... If you have styles that [should be] conditionally included [they] should be encapsulated in mixins, in 'module' or 'library' files. ... The main idea is that importing one such file will not output any css. This way, you can import these files redundantly so you can use the mixins wherever you need them.

Solution 4

There isn't currently a way to place import statements within if blocks, unfortunately.

The closest alternative I'm aware of is to use the additionalData field to add a preprocessor function to your webpack sass-loader config:

{
    loader: "sass-loader",
    options: {
        sassOptions: {
            includePaths: [...],
        },
        additionalData: (content: string, loaderContext)=>{
            // More info on available properties: https://webpack.js.org/api/loaders
            const {resourcePath, rootContext} = loaderContext;
            
            const finalPath = someCondition ? path1 : path2;
            return content.replace(/SomeDynamicPathPlaceholder/g, finalPath);
        },
    },
},

More info on the additionalData field here: https://webpack.js.org/loaders/sass-loader/#additionaldata

Solution 5

I know this is a seriously old question, but we recently implemented this in our own tiny UI framework like this:

ui-framework/config.scss

$components: (
    "component-a": true,
    "component-b": false
) !default;

// A bunch of other default config

ui-framework/main.scss

@import "component-a";
@import "component-b";

ui-framework/component-a.scss

@if (map-get($components, "component-a") {
    .component-a {
        // Bunch of code here
    }
}

ui-framework/component-b.scss

@if (map-get($components, "component-b") {
    .component-b {
        // Bunch of code here
    }
}

And then in each project:

a-project/main.scss

// NOTE: We only want component b in this project
$components: (
    "component-a": false,
    "component-b": true
);

@import "ui-framework/config.scss";
@import "ui-frameowrk/main.scss";

We don't do this for every single component, but the huge ones that aren't always in use (like slideshow, dialog, form related code etc).

Share:
34,859
woutvdd
Author by

woutvdd

Updated on December 03, 2021

Comments

  • woutvdd
    woutvdd over 2 years

    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".

  • woutvdd
    woutvdd over 11 years
    You mean like @if $load-complete-css { @include othercomponents; } @mixin othercomponents { @import "module1" ; @import "modules2"; } ? I have now the same error.. It's not possible to import in a mixin either
  • cimmanon
    cimmanon over 11 years
    Correct: the mixin in question cannot perform an import either. You have to place the entire contents of your files into a single mixin if you want to use it with @if.
  • woutvdd
    woutvdd over 11 years
    Ok so i think it would be better to make 2 sass project files myproject-full-modules.scss with all imports of all the modules and myproject-basics.scss with the essential modules the problem is, it's not DRY: If I want to disable a module I have to remove it on 2 files
  • cimmanon
    cimmanon over 11 years
    How much styling is there that's exclusive to one page? Splitting up the files and causing 2 HTTP requests is probably worse than having a single file that includes everything.
  • Marnen Laibow-Koser
    Marnen Laibow-Koser over 9 years
    @cimmanon Or not. Smaller files are independently cacheable. Two HTTP requests is no problem if one or the other file will be cached for future page loads. I tend to believe that the current fad of concatenating all CSS and JS for the whole site is very poor practice, caused by a failure to think about how to properly modularize.
  • Thomas
    Thomas almost 9 years
    I'm pretty stoked on this solution -- really clever thinking thank you!
  • thephpdev
    thephpdev over 7 years
    Do you know why they are reluctant? This functionality would be extremely helpful for me right now.
  • John Slegers
    John Slegers over 7 years
    @thephpdev : You might want to take a look at and contribute to the discussion that has been going on @ Github (see links hereabove). The more people request this feature, they more likely they'll eventually implement it ;-)
  • thephpdev
    thephpdev over 7 years
    Yeah, I did. And that's the key, "eventually". Probably won't happen. I saw something about them building some kind of new dependency management system. But that was three years ago. Doesn't look like anything is actually happening. So I just didn't really see the point. :)
  • John Slegers
    John Slegers over 7 years
    @thephpdev : Their inability to relate with what their users actually need and their unwillingness to implement features as important as dynamic dependencies have been bothering me for a long time, to the point where I actually considered writing my own preprocessor language... It sucks, but I guess we just have to live with if if we want to keep using Sass...
  • thephpdev
    thephpdev over 7 years
    indeed. Still prefer it to plain CSS, though haha.