SASS – 在多个文件中使用variables

我想保留一个中心.scss文件,它存储一个项目的所有SASSvariables定义。

// _master.scss $accent: #6D87A7; $error: #811702; $warning: #F9E055; $valid: #038144; // etc... 

由于其性质,该项目将有大量的CSS文件。 我在一个位置声明所有项目范围的样式variables是非常重要的。

有没有办法在SCSS做到这一点?

你可以这样做:

我有一个名为实用程序的文件夹,里面有一个名为_variables.scss的文件

在那个文件中,我声明这样的variables:

 $black: #000; $white: #fff; 

然后我有style.scss文件,我导入我所有的其他scss文件,像这样:

 // Utilities @import "utilities/variables"; // Base Rules @import "base/normalize"; @import "base/global"; 

那么,在我已经导入的任何文件中,我应该能够访问我已经声明的variables。

只要确保你在你想要使用的其他人之前导入variables文件。

这个答案显示了我如何结束使用这个和我碰到的额外陷阱。

我做了一个主SCSS文件。 该文件在开始时必须具有下划线,以便导入:

 // assets/_master.scss $accent: #6D87A7; $error: #811702; 

然后,在我所有其他.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; } 

重要

_master.scss文件中不要包含variables,函数声明和其他SASS特性。 如果您包含实际的CSS,则会在您导入主文件的每个文件中复制此CSS。

创build一个index.scss,你可以导入你所有的文件结构。 我会粘贴你从我的企业项目的索引,也许这将帮助其他如何在CSS结构文件:

 @import 'base/_reset'; @import 'helpers/_variables'; @import 'helpers/_mixins'; @import 'helpers/_functions'; @import 'helpers/_helpers'; @import 'helpers/_placeholders'; @import 'base/_typography'; @import 'pages/_versions'; @import 'pages/_recording'; @import 'pages/_lists'; @import 'pages/_global'; @import 'forms/_buttons'; @import 'forms/_inputs'; @import 'forms/_validators'; @import 'forms/_fieldsets'; @import 'sections/_header'; @import 'sections/_navigation'; @import 'sections/_sidebar-a'; @import 'sections/_sidebar-b'; @import 'sections/_footer'; @import 'vendors/_ui-grid'; @import 'components/_modals'; @import 'components/_tooltip'; @import 'components/_tables'; @import 'components/_datepickers'; 

你可以用吞咽/咕噜/ webpack等来观看它们,比如:

gulpfile.js

// SASS任务

 var gulp = require('gulp'); var sass = require('gulp-sass'); //var concat = require('gulp-concat'); var uglifycss = require('gulp-uglifycss'); var sourcemaps = require('gulp-sourcemaps'); gulp.task('styles', function(){ return gulp .src('sass/**/*.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(concat('styles.css')) .pipe(uglifycss({ "maxLineLen": 80, "uglyComments": true })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('./build/css/')); }); gulp.task('watch', function () { gulp.watch('sass/**/*.scss', ['styles']); }); gulp.task('default', ['watch']);