Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sass - Import variables into main file and have them available in other file that are imported into main

Say I have an index scss file in which all my other smaller scss partials are imported into:

@import "color-vars";
@import "scss_that_uses_the_color_vars";

scss_that_uses_the_color_vars looks as follows:

p {
   background-color: $mainColor;  // ERROR: undefined variable $mainColor
}

However, I did define $mainColor in color-vars which I imported before scss_that_uses_the_color_vars in the index file ... how can I make it work whilst preserving the modularity?

I say "whilst preserving modularity" because I don't want to simply insert @import "color-vars"; in scss_that_uses_the_color_vars, since that would make it very hard to debug when all my smaller modules import each other. I.e. that would result in a total mess! Therefore, I would like to define the flow of imports in the index file, but this, unfortunately, doesn't seem to be possible?

question from:https://stackoverflow.com/questions/65925240/import-variables-into-main-file-and-have-them-available-in-other-file-that-are-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For such purposes the @use rule should be the optimal decision.

Members (variables, functions, and mixins) loaded with @use are only visible in the stylesheet that loads them. Other stylesheets will need to write their own @use rules if they also want to access them. This helps make it easy to figure out exactly where each member is coming from.

// scss_that_uses_the_color_vars
@use 'color-vars';

p {
   background-color: $mainColor; 
}
// index
@forward 'scss_that_uses_the_color_vars'; // or `@import`, but read belows paragraph

On a side-note @import is deemed depricated, to ensure the functionality of your Sass code in the future, concidering to generally switch to @use or @forward might be worth the thought.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...