Search code examples
sass

How to handle import loops in Sass?


I have a main sass file named index.sass that defines some global variables such as colors and style the body, and a TitleBar.sass that style the title bar.

index.sass:

@use './TitleBar'

$primaryColor: blue

body:
  box-sizing: border-box
  width: 100%
  height: 100%
  padding-top: $titleBarHeight
  overflow: auto

TitleBar.sass

@use './index'

$titleBarHeight: 32px
  
.titleBar
  position: fixed
  top: 0
  left: 0
  box-sizing: border-box
  width: 100%
  height: $titleBarHeight
  background: $primaryColor

The issue is that I want to use $primaryColor which is defined in index.sass in TitleBar.sass and I want to use $titleBarHeight which is defined in TitleBar.sass in index.sass. To do so I have to import them into each other, but if I do that I have a loop import error. Is there a way to achieve that or should I define $titleBarHeight in index.sass?


Solution

  • As far as I know you need to break the loop manually by splitting the code up into different files.

    I found it a good rule-of-thumb to define local sass/scss variables for things that are never intended to be used outside the respective component-style; but to move all variables that are likely to affect other styles into dedicated constants files. Your $titleBarHeight and $primaryColor both are of the latter category.

    To illustrate this:

    // index.sass
    @import './page-layout'
    @import './title-bar'
    
    // page-layout.sass
    @use './colors'
    @use './dimensions'
    
    body:
      box-sizing: border-box
      width: 100%
      height: 100%
      padding-top: $titleBarHeight
      overflow: auto
    
    // title-bar.sass
    @use './colors'
    @use './dimensions'
    
    $nav-item-gap: 8px // only for local use
      
    .titleBar
      position: fixed
      top: 0
      left: 0
      box-sizing: border-box
      width: 100%
      height: $titleBarHeight
      background: $primaryColor
    
    .navContainer
      display: flex
      gap: $nav-item-gap
    
    // colors.sass
    $primaryColor: blue
    $secondaryColor: pink
    // etc.
    
    // dimensions.sass
    $titleBarHeight: 32px
    $pageFooterHeight: 16px
    $pageGutter: 64px
    // etc.