更新:如果计划实施该
export
解决方案,则必须 将其放置在单独的文件中,以防止在已编译的CSS代码中进行多余的导出。看这里。
我最近了解到,您可以像这样将样式从SCSS导出到JS:
_variables.scss
:export {
some-variable: 'some-value';
}
Run Code Online (Sandbox Code Playgroud)
app.js
import styles from 'core-styles/brand/_variables.scss';
Run Code Online (Sandbox Code Playgroud)
基于此,我_variables.scss
的格式如下:
/* Define all colours */
$some-color: #000;
$another-color: #000;
// Export the color palette to make it accessible to JS
:export {
some-color: $some-color;
another-color: $another-color;
}
Run Code Online (Sandbox Code Playgroud)
上述格式的问题在于,我必须在中重新定义每个变量export
。因此,我想知道是否有一种方法可以loop
自动遍历每个变量并将其导出到JS?
Que*_*ron 24
对已接受答案的一些改进:
使用驼峰式大小写,这样您就可以单独导出变量。
将@each
指令设置在外部,这样它就不会:export
为每个变量生成新的规则。
_variables.scss
$theme-colors: (
'someColor': #000,
'anotherColor': #FFF,
);
:export {
@each $key, $value in $theme-colors {
#{unquote($key)}: $value;
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序.js
$theme-colors: (
'someColor': #000,
'anotherColor': #FFF,
);
:export {
@each $key, $value in $theme-colors {
#{unquote($key)}: $value;
}
}
Run Code Online (Sandbox Code Playgroud)
旁注:我更喜欢在 Sass Maps 中使用引号,但您可以省略它们。
Lew*_*wis 18
从 Bootstrap 4 中获取提示,您可以将 SASS 映射与如下所示的循环组合在一起;
/* Define all colours */
$theme-colours: (
some-color: #000,
another-color: #000,
third-color: #000,
fourth-color: #000
)
@each $color, $value in $theme-colours {
:export{
$color: $value;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是Bootstrap 4 Docs 中的一些示例