国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Key Takeaways
Compiling Sass
Adding sourcemaps
Bringing Autoprefixer to the party
Release the docs!
I’m watching you
Adding the final touch
Final thoughts
Frequently Asked Questions (FAQs) about Gulp and SASS Workflow
How do I install Gulp and SASS for my project?
How do I compile my SASS files using Gulp?
How do I watch for changes in my SASS files and automatically compile them?
How do I handle errors in my SASS files?
How do I use Gulp to minify my CSS files?
Home Web Front-end JS Tutorial A Simple Gulp'y Workflow For Sass

A Simple Gulp'y Workflow For Sass

Feb 19, 2025 pm 12:40 PM

A Simple Gulp'y Workflow For Sass

Key Takeaways

  • A Gulp workflow can improve the Sass compilation time in large Rails projects, moving away from the asset pipeline and embracing the speed of LibSass.
  • The Gulp workflow includes Sass compilation with LibSass, generating sourcemaps for easier debugging, prefixing CSS with Autoprefixer, and generating Sass documentation with SassDoc.
  • The workflow can be further optimized by adding a watch task that monitors changes in stylesheets to recompile them, eliminating the need to manually run the sass task after every file save.
  • A ‘prod’ task can be created for deploying to production, which compiles Sass in compressed mode, prefixes CSS with Autoprefixer, regenerates SassDoc documentation, and avoids any sourcemaps.

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. :)

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).

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:

  • Unsurprisingly, Sass compilation with LibSass
  • Generating sourcemaps for easier debugging
  • Prefixing CSS with Autoprefixer
  • Generating Sass documentation with SassDoc

Compiling Sass

Watch AtoZ: Sass Learn Sass letter by letter A Simple Gulp'y Workflow For Sass Watch This Course Watch This Course

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:

$ <span>npm install gulp gulp-sass --save-dev</span>

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:

<span>var gulp = require('gulp');
</span><span>var sass = require('gulp-sass');</span>

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

$ <span>npm install gulp gulp-sass --save-dev</span>

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:

<span>var gulp = require('gulp');
</span><span>var sass = require('gulp-sass');</span>

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.

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.

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

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

And now let’s optimise our task:

<span>var sassOptions = {
</span>  <span>errLogToConsole: true,
</span>  <span>outputStyle: 'expanded'
</span><span>};
</span>
gulp<span>.task('sass', function () {
</span>  <span>return gulp
</span>    <span>.src(input)
</span>    <span>.pipe(sass(sassOptions).on('error', sass.logError))
</span>    <span>.pipe(gulp.dest(output));
</span><span>});</span>

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:

$ <span>npm install gulp-sourcemaps --save-dev</span>

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).

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.

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

<span>var gulp = require('gulp');
</span><span>var sass = require('gulp-sass');
</span><span>var sourcemaps = require('gulp-sourcemaps');
</span>
<span>// ... variables
</span>
gulp<span>.task('sass', function () {
</span>  <span>return gulp
</span>    <span>.src(input)
</span>    <span>.pipe(sourcemaps.init())
</span>    <span>.pipe(sass(sassOptions).on('error', sass.logError))
</span>    <span>.pipe(sourcemaps.write())
</span>    <span>.pipe(gulp.dest(output));
</span><span>});</span>

Then we add it to our task:

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

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

  • Browsers with over 1% market share,
  • Last 2 versions of all browsers,
  • Firefox ESR,
  • Opera 12.1

We can use our own configuration like so:

$ <span>npm install gulp-autoprefixer --save-dev</span>

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.

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

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.

$ <span>npm install gulp gulp-sass --save-dev</span>
<span>var gulp = require('gulp');
</span><span>var sass = require('gulp-sass');</span>

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.

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

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

<span>var sassOptions = {
</span>  <span>errLogToConsole: true,
</span>  <span>outputStyle: 'expanded'
</span><span>};
</span>
gulp<span>.task('sass', function () {
</span>  <span>return gulp
</span>    <span>.src(input)
</span>    <span>.pipe(sass(sassOptions).on('error', sass.logError))
</span>    <span>.pipe(gulp.dest(output));
</span><span>});</span>

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.

$ <span>npm install gulp-sourcemaps --save-dev</span>

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.

Adding the final touch

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

<span>var gulp = require('gulp');
</span><span>var sass = require('gulp-sass');
</span><span>var sourcemaps = require('gulp-sourcemaps');
</span>
<span>// ... variables
</span>
gulp<span>.task('sass', function () {
</span>  <span>return gulp
</span>    <span>.src(input)
</span>    <span>.pipe(sourcemaps.init())
</span>    <span>.pipe(sass(sassOptions).on('error', sass.logError))
</span>    <span>.pipe(sourcemaps.write())
</span>    <span>.pipe(gulp.dest(output));
</span><span>});</span>

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).

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:

  • Compile Sass in compressed mode
  • Prefix CSS with Autoprefixer
  • Regenerate SassDoc documentation
  • Avoid any sourcemaps
gulp<span>.task('sass', function () {
</span>  <span>return gulp
</span>    <span>.src(input)
</span>    <span>.pipe(sourcemaps.init())
</span>    <span>.pipe(sass(sassOptions).on('error', sass.logError))
</span>    <span>.pipe(sourcemaps.write('./stylesheets/maps'))
</span>    <span>.pipe(gulp.dest(output));
</span><span>});</span>

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?

Frequently Asked Questions (FAQs) about Gulp and SASS Workflow

How do I install Gulp and SASS for my project?

To install Gulp and SASS for your project, you need to have Node.js and npm installed on your computer. Once you have these, you can install Gulp globally by running the command npm install --global gulp-cli in your terminal. After that, navigate to your project directory and run npm init to create a package.json file. Then, install Gulp and gulp-sass in your project by running npm install --save-dev gulp gulp-sass.

How do I compile my SASS files using Gulp?

To compile your SASS files using Gulp, you need to create a Gulp task. In your gulpfile.js, you can create a task named ‘sass’ that will compile your SASS files into CSS. Here’s a simple example of how to do this:

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

gulp.task('sass', function () {
return gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});

This task will take all .scss files in your sass directory, compile them into CSS using gulp-sass, and output the resulting CSS files in your css directory.

How do I watch for changes in my SASS files and automatically compile them?

Gulp provides a method called watch that you can use to automatically run tasks whenever files are changed. Here’s how you can modify the ‘sass’ task to watch for changes:

gulp.task('sass', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});

Now, whenever you save a .scss file in your sass directory, the ‘sass’ task will automatically run and compile your SASS files into CSS.

How do I handle errors in my SASS files?

When compiling SASS files, you might encounter syntax errors. You can handle these errors using the on method provided by gulp-sass. Here’s how you can modify the ‘sass’ task to log errors:

gulp.task('sass', function () {
return gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});

Now, whenever there’s a syntax error in your SASS files, gulp-sass will log the error and continue with the task.

How do I use Gulp to minify my CSS files?

To minify your CSS files, you can use a Gulp plugin called gulp-clean-css. First, install it in your project by running npm install --save-dev gulp-clean-css. Then, you can create a task that will minify your CSS files:

var cleanCSS = require('gulp-clean-css');

gulp.task('minify-css', () => {
return gulp.src('styles/*.css')
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest('dist'));
});

This task will take all .css files in your styles directory, minify them using gulp-clean-css, and output the resulting minified CSS files in your dist directory.

The above is the detailed content of A Simple Gulp'y Workflow For Sass. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

See all articles