Follow first 3 steps from this post and install gulp and required packages.
Step 4: Sass Packages
We can use gulp-sass plugin to compile Sass files and gulp-clean-css plugin to minify the compiled files.
npm install sass gulp-sass gulp-clean-css gulp-sourcemaps gulp-postcss autoprefixer --save-dev
autoprefixer and gulp-postcss will help with vendor prefixing and gulp-sourcemaps… you know why we need that!
Step 5: Compile function
5.1: Import packages
Let’s import the installed packages to gulpfile.babel.js:
//gulpfile.babel.js
import { src, dest } from 'gulp';
import yargs from 'yargs';
import cleanCss from 'gulp-clean-css';
import gulpif from 'gulp-if';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer';
const PRODUCTION = yargs.argv.prod;
var sass = require("gulp-sass")(require("sass"));
...
...
5.2: Write a function
Let’s write a function to compile Sass files and save it to a specific folder.
//gulpfile.babel.js
...
...
export const compileSass = () => {
return src('assets/sass/main.scss')
.pipe(gulpif(!PRODUCTION, sourcemaps.init()))
.pipe(sass().on('error', sass.logError))
.pipe(gulpif(PRODUCTION, postcss([ autoprefixer ])))
.pipe(gulpif(PRODUCTION, cleanCss({compatibility:'ie8'})))
.pipe(gulpif(!PRODUCTION, sourcemaps.write()))
.pipe(dest('assets/css'));
}
Using the code above, we read the file using src and using dest we create the compiled css file. We’re also inserting sourcemap info for dev mode.
Using gulpif, we’re only minifying the css file, but only for the production mode.
This is how you can pass the production mode:
gulp compileSass --prod
Without –prod, it’ll just use dev mode by default.
5.1: Multiple Source Files
You can pass multiple files as an array like this:
//gulpfile.babel.js
...
...
return src(['assets/sass/main.scss', 'assets/sass/projects.scss'])
...
...
Step 6: Watch Sass
We need to import watch in gulpfile.babel.js and write a function:
//gulpfile.babel.js
...
import { src, dest, watch } from 'gulp';
...
...
export const watchSass = () => {
watch('assets/sass/**/*.scss', styles);
}
To call the function, use this command:
gulp watchSass
basics CLI command-line guide gulp install sass task runner