gulp sass_Sass的简单Gulp'y工作流程

gulp sass

I have recently been in charge of optimizing the Sass side of quite a big Rails project, and one of most important things to do was to improve the compilation time. Because of the Sass architecture in place and the fact that Ruby Sass (through the Rails asset pipeline in this case) tends to be slow when dealing with a huge number of files, it could take up to 40 seconds to compile the stylesheets. Talk about a fast development process. :)

我最近负责优化一个相当大的Rails项目的Sass方面,最重要的事情之一就是缩短编译时间。 由于采用了Sass体系结构,并且在处理大量文件时,Ruby Sass(在本例中是通过Rails资产管道)往往很慢,因此编译样式表可能需要40秒钟的时间。 讨论快速的开发过程。 :)

My idea was to move away from the asset pipeline and embrace the speed of LibSass. To make things easier I decided to go with a simple Gulp workflow. It was the first time I would be using Gulp, and I must say it was quite an enjoyable experience (which was not the case for Grunt as far as I am concerned).

我的想法是离开资产管道,并接受LibSass的速度。 为了简化工作,我决定使用简单的Gulp工作流程。 这是我第一次使用Gulp,我必须说这是一次非常愉快的经历(就我而言,Grunt并非如此)。

In this short article, let’s just have a quick tour on how to set up a Gulp’y workflow to work with Sass. Here is what we will include:

在这篇简短的文章中,让我们快速浏览一下如何设置Gulp'y工作流程以与Sass一起使用。 这是我们将包括的内容:

  • Unsurprisingly, Sass compilation with LibSass

    毫不奇怪,使用LibSass进行Sass编译
  • Generating sourcemaps for easier debugging

    生成源映射以简化调试
  • Prefixing CSS with Autoprefixer

    使用自动前缀对CSS进行前缀

  • Generating Sass documentation with SassDoc

    使用SassDoc生成Sass文档

编译Sass (Compiling Sass)

The first thing to do is to install the dependencies and to create a Gulpfile.js. We will need Gulp (no shit, Sherlock), but also gulp-sass to compile our stylesheets:

首先要做的是安装依赖关系并创建一个Gulpfile.js 。 我们将需要Gulp(不拉屎,Sherlock),但也需要gulp-sass来编译样式表:

$ npm install gulp gulp-sass --save-dev

This line tells npm to install both gulp and gulp-sass packages as development dependencies. You can now find them in the devDependencies object of your package.json. And the Gulpfile.js:

此行告诉npm安装gulpgulp-sass软件包作为开发依赖项。 现在,您可以在package.jsondevDependencies对象中找到它们。 还有Gulpfile.js

var gulp = require('gulp');
var sass = require('gulp-sass');

Wow, that was short. What we need now is a task to run Sass (actually gulp-sass) on our stylesheets folder.

哇,太短了。 现在,我们需要执行的任务是在样式表文件夹中运行Sass(实际上是gulp-sass )。

var input = './stylesheets/**/*.scss';
var output = './public/css';

gulp.task('sass', function () {
  return gulp
    // Find all `.scss` files from the `stylesheets/` folder
    .src(input)
    // Run Sass on those files
    .pipe(sass())
    // Write the resulting CSS in the output folder
    .pipe(gulp.dest(output));
});

That’s it! We can now compile our stylesheets using LibSass thanks to a very minimal Gulp task. What about that? We can pass options to gulp-sass to compile stylesheets in expanded mode and to print errors in console:

而已! 由于非常简单的Gulp任务,我们现在可以使用LibSass编译样式表。 那个怎么样? 我们可以将选项传递给gulp-sass以在扩展模式下编译样式表并在控制台中打印错误:

var sassOptions = {
  errLogToConsole: true,
  outputStyle: 'expanded'
};

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(gulp.dest(output));
});

添加源图 (Adding sourcemaps)

So far, so good. Now, what about generating sourcemaps? In case you don’t know what sourcemaps are, it basically is a way to map compressed production sources with expanded development sources in order to make debugging live code easier. They are not restricted to CSS at all, sourcemaps can be used in JavaScript as well.

到目前为止,一切都很好。 现在,生成源图怎么样? 如果您不知道什么是源映射,则基本上是一种将压缩的生产源与扩展的开发源进行映射的方法,以使调试实时代码更加容易。 它们根本不限于CSS,sourcemap也可以在JavaScript中使用。

We have a nice article about sourcemaps here at SitePoint. Feel free to give it a read before going on if you feel a bit short on the understanding of sourcemaps.

我们在SitePoint上有一篇有关sourcemaps的不错的文章。 如果您对源映射的理解有些短,请在继续阅读之前先对其进行阅读。

Okay, so to add sourcemaps generation to our task, we need to install gulp-sourcemaps:

好的,因此要将sourcemaps生成添加到我们的任务中,我们需要安装gulp-sourcemaps

$ npm install gulp-sourcemaps --save-dev

And now let’s optimise our task:

现在让我们优化我们的任务:

var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');

// ... variables

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(output));
});

By default, gulp-sourcemaps writes the sourcemaps inline in the compiled CSS files. Depending on the project setup, we might want to write them in separate files, in which case we can specify a path relative to the gulp.dest() destination in the sourcemaps.write()function like:

默认情况下, gulp-sourcemaps将源映射内联地写入已编译CSS文件中。 根据项目设置,我们可能希望将它们写入单独的文件中,在这种情况下,我们可以在sourcemaps.write()函数中指定相对于gulp.dest()目标的路径,例如:

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(sourcemaps.write('./stylesheets/maps'))
    .pipe(gulp.dest(output));
});

携带Autoprefixer参加聚会 (Bringing Autoprefixer to the party)

I won’t go into much detail about why using Autoprefixer is better than writing vendor by hand (or with a mixin which is basically the same thing), but roughly Autoprefixer is a post-processing step meaning it actually updates already compiled stylesheets to add relevant prefixes based on an up-to-date database and a given configuration. In other words, you tell Autoprefixer which browsers you want to support, and it adds only relevant prefixes to the stylesheets. Zero effort, perfect support (please remind me to patent this catch phrase).

我不会详细说明为什么使用Autoprefixer优于手动编写供应商(或使用基本上相同的mixin),但是大致来说Autoprefixer是后期处理步骤,这意味着它实际上会更新已编译的样式表以添加基于最新数据库和给定配置的相关前缀。 换句话说,您告诉Autoprefixer您要支持哪些浏览器,并且它仅在样式表中添加相关的前缀。 零努力,完美的支持(请提醒我为这个流行语申请专利)。

To include Autoprefixer in our Gulp’y workflow, we only need it to pipe it after Sass has done its thing. Then Autoprefixer updates the stylesheets to add prefixes.

要将Autoprefixer包含在Gulp'y工作流程中,我们只需要在Sass完成其工作后将其通过管道传输即可。 然后,Autoprefixer将更新样式表以添加前缀。

First, let’s install it (you get the gist by now):

首先,让我们安装它(您现在已经掌握了要点):

$ npm install gulp-autoprefixer --save-dev

Then we add it to our task:

然后,将其添加到我们的任务中:

var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');

// ... variables

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(autoprefixer())
    .pipe(gulp.dest(output));
});

Right now, we run with the default configuration from Autoprefixer which is

现在,我们使用Autoprefixer的默认配置运行

  • Browsers with over 1% market share,

    具有1%以上市场份额的浏览器,
  • Last 2 versions of all browsers,

    所有浏览器的最后2个版本,
  • Firefox ESR,

    Firefox ESR,
  • Opera 12.1

    Opera 12.1

We can use our own configuration like so:

我们可以这样使用我们自己的配置:

var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');

// ... variables
var autoprefixerOptions = {
  browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
};

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(gulp.dest(output));
});

发布文档! (Release the docs!)

The last, but not least, tool to add to our workflow, Sass documentation generation with SassDoc. SassDoc is to Sass what JSDoc is to JavaScript: a documentation tool. It parses your stylesheets looking for comment blocks documenting variables, mixins, functions and placeholders.

添加到我们的工作流程中的最后一个(但并非最不重要)工具是使用SassDoc生成Sass文档。 SassDoc对Sass意味着JSDoc对JavaScript:一种文档工具。 它解析您的样式表,以查找记录变量,混合,函数和占位符的注释块。

If your project uses SassDoc (it should!), you can add the automatic documentation generation in your Gulp workflow.

如果您的项目使用SassDoc(应该使用!),则可以在Gulp工作流程中添加自动文档生成。

The cool thing with SassDoc is that it can be piped directly in Gulp because its API is Gulp compatible. So you don’t actually have a gulp-sassdoc plugin.

SassDoc的酷之处在于它可以直接在Gulp中进行管道传输,因为其API与Gulp兼容。 因此,您实际上没有gulp-sassdoc插件。

npm install sassdoc --save-dev
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var sassdoc = require('sassdoc');

// ... variables

gulp.task('sass', function () {
  return gulp
    .src(input)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(gulp.dest(output))
    .pipe(sassdoc())
    // Release the pressure back and trigger flowing mode (drain)
    // See: http://sassdoc.com/gulp/#drain-event
    .resume();
});

Note that depending on the size of your project and the number of documented items, SassDoc can take up to a few of seconds to run (rarely above 3 as far as I’ve noticed), so you might want to have a separate task for this.

请注意,根据项目的大小和记录的项目数,SassDoc可能需要花费几秒钟的时间运行(据我所知,它实际上很少超过3秒钟),因此您可能希望为这个。

gulp.task('sassdoc', function () {
  return gulp
    .src(input)
    .pipe(sassdoc())
    .resume();
});

Again, we use the default configuration but we can use our own if we want to.

同样,我们使用默认配置,但如果需要,可以使用自己的配置。

var sassdocOptions = {
  dest: './public/sassdoc'
};

gulp.task('sassdoc', function () {
  return gulp
    .src(input)
    .pipe(sassdoc(sassdocOptions))
    .resume();
});

我在看着你 (I’m watching you)

There is still something we can do before leaving: creating a watch task. The point of this task would be to watch for changes in stylesheets to recompile them again. It is very convenient when working on the Sass side of the project so you don’t have to run the sass task by hand every time you save a file.

在离开之前,我们仍然可以做些事情:创建watch任务。 该任务的重点是监视样式表中的更改以再次重新编译它们。 当在项目的Sass端工作时,这非常方便,因此您不必在每次保存文件时都手动运行sass任务。

gulp.task('watch', function() {
  return gulp
    // Watch the input folder for change,
    // and run `sass` task when something happens
    .watch(input, ['sass'])
    // When there is a change,
    // log a message in the console
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

Here is another reason why I recommend not including SassDoc in the sass task: you probably don’t want to regenerate the docs every time you touch a stylesheet. This is likely something you want to do on build or push, maybe with a pre-commit hook.

这是我建议在sass任务中不包括SassDoc的另一个原因:您可能不想每次触摸样式表时都重新生成文档。 您可能希望在构建或推送时执行此操作,也许要使用预提交挂钩。

添加最后的印象 (Adding the final touch)

A last, yet important, thing to think about: running sass in the default task.

最后要考虑的重要一件事:在默认任务中运行sass

gulp.task('default', ['sass', 'watch' /*, possible other tasks... */]);

The array passed as second argument of the task(..) function is a list of dependency tasks. Basically, it tells Gulp to run those tasks before running the one specified as a third argument (if any).

作为task(..)函数的第二个参数传递的数组是依赖项任务的列表。 基本上,它告诉Gulp运行那些任务,然后再运行指定为第三个参数的任务(如果有的话)。

Also, we could probably create a prod task that could be run right before deploying to production (maybe with a git hook). This task should:

另外,我们可能会创建一个prod任务,该任务可以在部署到生产之前就运行(可能带有git hook)。 该任务应:

  • Compile Sass in compressed mode

    以压缩模式编译Sass
  • Prefix CSS with Autoprefixer

    带自动前缀的前缀CSS
  • Regenerate SassDoc documentation

    重新生成SassDoc文档
  • Avoid any sourcemaps

    避免任何源图
gulp.task('prod', ['sassdoc'], function () {
  return gulp
    .src(input)
    .pipe(sass({ outputStyle: 'compressed' }))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(gulp.dest(output));
});

最后的想法 (Final thoughts)

That’s it folks! In just a couple of minutes and a few lines of JavaScript, we have managed to create a powerful little Gulp workflow. You can find the full file here. What would you add to it?

就是这样! 在短短的几分钟和几行JavaScript中,我们就成功创建了一个功能强大的Gulp小工作流程。 您可以在此处找到完整文件 。 您会添加什么?

翻译自: https://www.sitepoint.com/simple-gulpy-workflow-sass/

gulp sass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值