背景
考虑以下 _variables.scss
文件:
/* Define all colours */
$white: #fff;
$black: #000;
$grey: #ccc;
// etc...
// Export the color palette to make it accessible to JS
:export {
white: $white;
black: $black;
grey: $grey;
// etc...
}
上述代码的目的是通过像这样导入的方式使 SCSS 变量可用于 Javascript:
import variables from 'variables.scss';
查看更详细的描述here .
问题
现在考虑以下模板(我以 Vue.js 模板为例,但这与许多框架相关):
<!-- Template here... -->
<style lang="scss" scoped>
// Import Partials
@import "~core-styles/brand/_variables.scss";
@import "~core-styles/brand/_mixins.scss";
// Styles here...
</style>
在上面的示例中,我使用了 scoped
属性,因为这演示了即将出现的问题的最坏情况,但即使没有 scoped
问题仍然存在相关。
上面的 SCSS 将编译成如下内容:
[data-v-9a6487c0]:export {
white: #fff;
black: #000;
grey: #ccc;
// etc...
}
此外,通过 scoped
属性,每次 将 _variables.scss
导入到模板中时,这将重复,并且 可能会导致额外的冗余代码。在某些情况下,对于大型应用程序(许多组件和大型调色板),这实际上可以添加 000 行完全冗余的代码。
我的问题
有没有办法将 SCSS 变量导出到 Javascript 而不将它们导出到 CSS?
潜在(脏)解决方案
理想情况下,我试图避免使用一个名为 _export.scss
的单独文件的解决方案,它的目的只是将所有 SCSS 变量导出到 JS,但它被排除在外CSS 构建...
只是为了扩展上面的 dirty 解决方案,这就是我目前正在使用的方法(在我的例子中,在一个标准大小的网站上,到目前为止,它已经为我节省了大约 600 行冗余 CSS代码):
_export.scss
/*
|--------------------------------------------------------------------------
| SASS Export
|--------------------------------------------------------------------------
|
| Define any variables that should be exported to Javascript. This file
| is excluded from the CSS builds in order to prevent the variables from
| being exported to CSS.
|
*/
@import "variables";
:export {
// Export the color palette to make it accessible to JS
white: #fff;
black: #000;
grey: #ccc;
// etc...
}
然后,在我的 Javascript 中,我不是从 _variables.scss
导入,而是从 _export.scss
导入,如下所示:
import styles from 'core-styles/brand/_export.scss';
最后,export
语句现在可以从 _variables.scss
文件中删除,从而阻止编译的 CSS export
代码。
注意:_export.scss
文件必须从SCSS 编译中排除!
最佳答案
Note: I have posted this answer because it seems there is no better solution, however, if someone subsequently provides a better solution, I will be more than happy to accept it.
似乎唯一真正的解决方案是从 _variables.scss
文件中提取 export
语句并将其放入自己的 _export 中。 scss
文件,该文件随后将不包含在 SCSS 编译中。
这看起来像这样:
_variables.scss - 包含在 SCSS 编译中
/* Define all colours */
$white: #fff;
$black: #000;
$grey: #ccc;
// etc...
_export.scss - 不包含在 SCSS 编译中
@import "variables";
:export {
// Export the color palette to make it accessible to JS
white: #fff;
black: #000;
grey: #ccc;
// etc...
}
然后你的 app.scss
(我使用 brand.scss
)文件看起来像这样(注意没有 @include "export";
):
@import "variables";
@import "mixins";
@import "core";
@import "animations";
// etc...
然后,_export.scss
在 JavaScript 中被简单地引用仅(注意 core-styles
只是我使用的别名在我的元素中):
import styles from 'core-styles/brand/_export.scss';
关于javascript - 将 SASS/SCSS 变量导出到 Javascript,而不将它们导出到 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57536228/