Skip to content

Feature request: @import-once #156

Description

@seanofw

I've used Sass on a number of projects now with great success, and finally convinced my company to use it on our flagship product --- a massive web application --- to make our 120,000 lines of CSS more manageable.

In doing so, I've found that there's a feature that would make for a really nice addition: The ability to mark some files with an "@import-once" directive, which causes that file to be imported only once no matter how many different other files import it.

Consider this scenario:

  • _SharedBaseStuff.scss has a bunch of base definitions.
  • _FooWidget.scss imports _SharedBaseStuff.scss
  • _BarWidget.scss imports _SharedBaseStuff.scss
  • YourPage.scss imports _FooWidget.scss
  • MyPage.scss imports _BarWidget.scss
  • TheirPage.scss imports both _FooWidget.scss and _BarWidget.scss

Without doing anything else, TheirPage.css will end up with two copies of any CSS found in _SharedBaseStuff.scss, which is undesirable. It'd be far better if inside _SharedBaseStuff.scss, you could just declare @import-once; at the top, which would ensure you only get the first copy in the output no matter how many times it's imported. (By definition, @import-once could not be appear inside an imported file that is nested within another selector or mixin; it could only appear at the root.)

(Yes, this is a real scenario on our huge site. In fact, our real-world scenarios are far uglier, with some .scss files able to be imported dozens of times or more by a single page's stylesheet.)

Currently, a little function like this can be used to implement a workaround:

$imported-once-files: ();

@function import-once($name) {
    @if index($imported-once-files, $name) {
        @return false;
    }
    $imported-once-files: append($imported-once-files, $name);
    @return true;
}

And then used like this:

@if import-once("_SharedBaseStuff.scss") {

    ...declare stuff that will only be imported once...

}

That works, but for large filesets with lots of imports, it's inefficient. Having a simple global @import-once; directive would make this much simpler.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions