您需要使用!default 关键字。
与!default
/* @file _variable.scss */
$theme_color: red !default;
$theme_shadow: 1px 1px 2px $theme_color !default;
/* @file styles.scss */
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
/* @file corporate.scss */
// I override the color BEFORE the loading of my variables declaration.
$theme_color: blue;
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
// Specific rule
.corporate-thing {
box-shadow: $theme_shadow;
}
CSS 输出
/* @file styles.scss */
.foo {
color: red;
box-shadow: 1px 1px 2px red;
}
/* @file corporate.scss */
.foo {
color: blue;
box-shadow: 1px 1px 2px blue;
}
.corporate-thing {
box-shadow: 1px 1px 2px blue;
}
没有!default
如果不使用!default,则每次调用_variable.scss时都会覆盖该变量:
/* @file _variable.scss */
$theme_color: red;
$theme_shadow: 1px 1px 2px $theme_color;
/* @file styles.scss */
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
/* @file corporate.scss */
$theme_color: blue;
// Now, $theme_color will be overwritten with the `red` value
// because of the absence of the `!default` keyword.
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
// Specific rule
.corporate-thing {
box-shadow: $theme_shadow;
}
CSS 输出
/* @file styles.scss */
.foo {
color: red;
box-shadow: 1px 1px 2px red;
}
/* @file corporate.scss */
.foo {
color: red;
box-shadow: 1px 1px 2px red;
}
.corporate-thing {
box-shadow: 1px 1px 2px red;
}
最终错误情况:加载后改变颜色_variable.scss
/* @file _variable.scss */
$theme_color: red;
$theme_shadow: 1px 1px 2px $theme_color;
/* @file styles.scss */
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
/* @file corporate.scss */
@import 'variable';
$theme_color: blue; // AFTER
.foo {
color: $theme_color;
// In this case, $theme_shadow is not overwritten with the new value
// of $theme_color and keeps it value to 'red'.
box-shadow: $theme_shadow;
}
// Specific rule
.corporate-thing {
box-shadow: $theme_shadow;
}
CSS 输出
/* @file styles.scss */
.foo {
color: red;
box-shadow: 1px 1px 2px red;
}
/* @file corporate.scss */
.foo {
color: blue; // OK: blue
box-shadow: 1px 1px 2px red; // KO: red
}
.corporate-thing {
box-shadow: 1px 1px 2px red; // KO: red
}
奖金
其实可以直接从corporate.scss导入styles.scss:
/* @file _variable.scss */
$theme_color: red !default;
$theme_shadow: 1px 1px 2px $theme_color !default;
/* @file styles.scss */
@import 'variable';
.foo {
color: $theme_color;
box-shadow: $theme_shadow;
}
/* @file corporate.scss */
// I override the color BEFORE the loading of my main stylesheet
$theme_color: blue;
// Now I have to generate the same code that `style.css`, so the
// easiest way to do it is to directly import it.
@import 'styles';
// Specific rule
.corporate-thing {
box-shadow: $theme_shadow;
}