Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function for SASS/SCSS to avoid duplicate imports and redundant generated CSS. See http://paul.wellnerbou.de/2015/05/18/avoid-multiple-imports-of-the-same-scss-file-with-sass/ for more details.
/* If this function is imported, you can import scss files using:
@if not-imported("your-file") { @import "your-file"; }
*/
$imported-once-files: () !default;
@function not-imported($name) {
$imported-once-files: $imported-once-files !global;
$module_index: index($imported-once-files, $name);
@if (($module_index == null) or ($module_index == false)) {
$imported-once-files: append($imported-once-files, $name);
@return true;
}
@return false;
}
@greaveselliott

This comment has been minimized.

Copy link

greaveselliott commented Oct 11, 2017

Great idea - unfortunately, this doesn't quite work for me. I run into the following error:
"Import directives may not be used within control directives or mixins. " any idea's?

@cscuderi

This comment has been minimized.

Copy link

cscuderi commented Apr 25, 2018

I get the same issue as greaveselliott above.

@hcomnetworkers

This comment has been minimized.

Copy link

hcomnetworkers commented Nov 27, 2018

This code does no longer work.
You may want to use:

$imported-once-files: () !default;

@function not-imported($name) {
  $module_index: index($imported-once-files, $name);
  @if (($module_index == null) or ($module_index == false)) {
    $imported-once-files: append($imported-once-files, $name) !global;
    @return true;
  }
  @return false;
}
@mritzman-dg

This comment has been minimized.

Copy link

mritzman-dg commented Jan 17, 2019

I'm also getting the same error as well

ERROR in ./src/sass/index.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@if not-imported("helpers/import-once-workaround") { @import "helpers/import-once-workaround"; }
                                                    ^
      Import directives may not be used within control directives or mixins.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment