我想保留一个中心.scss文件,该文件存储项目的所有SASS变量定义.
// _master.scss
$accent: #6D87A7;
$error: #811702;
$warning: #F9E055;
$valid: #038144;
// etc...
Run Code Online (Sandbox Code Playgroud)
由于其性质,该项目将包含大量CSS文件.重要的是我在一个位置声明所有项目范围的样式变量.
有没有办法在SCSS中做到这一点?
Joe*_*oel 293
你可以这样做:
我有一个名为utilities的文件夹,里面有一个名为_variables.scss的文件
在该文件中我声明变量如下:
$black: #000;
$white: #fff;
Run Code Online (Sandbox Code Playgroud)
然后我有style.scss文件,我在其中导入我的所有其他scss文件,如下所示:
// Utilities
@import "utilities/variables";
// Base Rules
@import "base/normalize";
@import "base/global";
Run Code Online (Sandbox Code Playgroud)
然后,在我导入的任何文件中,我应该能够访问我声明的变量.
只需确保在您想要使用它的任何其他文件之前导入变量文件.
whi*_*ode 89
这个问题很久以前就被问到了,所以我想我会发布一个更新的答案。
您现在应该避免使用@import. 取自文档:
Sass 将在未来几年逐步淘汰它,并最终将其从语言中完全删除。更喜欢@use 规则。
您现在应该使用@use如下所示:
_variables.scss
$text-colour: #262626;
Run Code Online (Sandbox Code Playgroud)
_otherFile.scss
@use 'variables'; // Path to _variables.scss Notice how we don't include the underscore or file extension
body {
// namespace.$variable-name
// namespace is just the last component of its URL without a file extension
color: variables.$text-colour;
}
Run Code Online (Sandbox Code Playgroud)
您还可以为命名空间创建别名:
_otherFile.scss
@use 'variables' as v;
body {
// alias.$variable-name
color: v.$text-colour;
}
Run Code Online (Sandbox Code Playgroud)
编辑正如@und3rdg 在撰写本文时(2020 年 11 月)所指出的,@use目前仅适用于 Dart Sass,而不适用于LibSass(现已弃用)或 Ruby Sass。有关最新兼容性,请参阅https://sass-lang.com/documentation/at-rules/use
dth*_*ree 75
这个答案显示了我最终如何使用这个以及我遇到的额外陷阱.
我制作了一个主SCSS文件.此文件必须在开头有一个下划线才能导入:
// assets/_master.scss
$accent: #6D87A7;
$error: #811702;
Run Code Online (Sandbox Code Playgroud)
然后,在我所有其他.SCSS文件的标题中,我导入主文件:
// When importing the master, you leave out the underscore, and it
// will look for a file with the underscore. This prevents the SCSS
// compiler from generating a CSS file from it.
@import "assets/master";
// Then do the rest of my CSS afterwards:
.text { color: $accent; }
Run Code Online (Sandbox Code Playgroud)
除文件中的变量,函数声明和其他SASS功能外,不要包含任何内容_master.scss.如果您包含实际的CSS,它将在您导入master的每个文件中复制此CSS.
小智 5
在 Angular v10 中,我做了类似的事情,首先创建一个master.scss文件并包含以下变量:
master.scss文件:
$theme: blue;
$button_color: red;
$label_color: gray;
Run Code Online (Sandbox Code Playgroud)
然后我将master.scss文件导入style.scss到顶部:
style.scss 文件:
@use './master' as m;
Run Code Online (Sandbox Code Playgroud)
确保master.scss在顶部导入。
m是命名空间的别名;
使用@use而不是@import根据下面的官方文档:
https://sass-lang.com/documentation/at-rules/import
然后在您的styles.scss文件中您可以使用master.scss如下定义的任何变量:
someClass {
backgroud-color: m.$theme;
color: m.$button_color;
}
Run Code Online (Sandbox Code Playgroud)
希望它会有所帮助...
快乐编码:)