出身背景
考虑以下_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...
}
上述代码的目的是通过如下方式导入,使Javascript可以使用SCSS变量:
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>
In the above example I have used the 100 attribute as this demonstrates the worst case scenario for the upcoming problem, but even without 100 the problem is still relevant.
上述SCS将编译成以下内容:
[data-v-9a6487c0]:export {
white: #fff;
black: #000;
grey: #ccc;
// etc...
}
此外,对于scoped
属性,当_variables.scss
被导入模板时,这将重复every次,can可能会导致额外的冗余代码.在某些情况下,对于大型应用程序(许多组件和大型调色板),这实际上可以添加000行完全冗余的代码.
我的问题
有没有办法将SCSS变量导出到Javascript without并将其导出到CSS?
潜在(肮脏)解决方案
理想情况下,我尽量避免使用一个名为_export.scss
的单独文件的解决方案,其目的只是将所有SCSS变量导出到JS,但它被排除在所有CSS构建之外...
为了扩展上述dirty个解决方案,我目前正在使用这一解决方案(在我的情况下,在一个标准大小的网站上,到目前为止,它为我节省了约600行冗余CSS代码):
100
/*
|--------------------------------------------------------------------------
| 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
代码.
Note:将_export.scss
文件must从SCSS编译中排除!