1

In practical applications, we generally use CSS preprocessors to write CSS code, such as Less and Sass languages. By parsing scripts into CSS scripting languages, we can reduce CSS duplication and save time.

In this section, we will learn how to compile Less and Sass into CSS code through gulp. The gulp-less plugin is needed to compile Less into CSS, and the gulp-ruby-sass plugin is needed to compile Sass into CSS.

Compile Less into CSS

For example, there is a style.less file in the less folder under the project root directory. The content of the file is as follows:

div{
    color: #ccc;
    a{
        color: white;
        font-size: 16px;
    }
    p{
        font-size: 14px;
        line-height: 30px;
    }
}

We need to compile this style.less file code into CSS code.

First, you need to install the gulp-less plug-in, the installation command is as follows:

npm install gulp-less

After installing the plug-in, we can create a command in the gulpfile.js file, the code is as follows:

// 获取 gulp
var gulp = require('gulp')
var gulp_less = require('gulp-less')

gulp.task('less', function(cb) {
    gulp.src('less/*.less')
        .pipe(gulp_less())
        .pipe(gulp.dest('dist/css'))
        cb()
})

Then we execute the gulp less command:


At this point, we will see that a style.css file is generated in the css folder under the dist directory. The content of the file is as follows. This is the CSS code compiled by less:

div {
  color: #ccc;
}
div a {
  color: white;
  font-size: 16px;
}
div p {
  font-size: 14px;
  line-height: 30px;
}




Compile Sass to CSS

Compiling Sass code into CSS code is actually similar to compiling Less into CSS, except that the plug-ins used are different, and a gulp-ruby-sass plug-in is needed.

The installation command is as follows:

npm install gulp-ruby-sass

Then the same is to create a task:

// 获取 gulp
var gulp = require('gulp')
var gulp_sass = require('gulp-ruby-sass')

gulp.task('sass', function(cb) {
    return gulp_sass('sass/*.scss')
    .on('error', function(err){
        console.error('Error!', err.message);
    })
    .pipe(gulp.dest('dist/css'))
    cb()
})

Execute the gulp sass command, the Sass file will be successfully compiled into CSS.

Link: https://www.9xkd.com/


知否
221 声望177 粉丝

Skrike while the iron is hot.