I
I
Ivan Medvedev2021-09-08 05:23:18
Sass
Ivan Medvedev, 2021-09-08 05:23:18

How to add SCSS preprocessor to Gulp?

Hi guys! Today I wrote my first Gulp build. Not without the help of YouTube and documentation. It turned out to implement SASS, but I write in SCSS.

The question is, how do I embed SCSS so that the styles compile correctly into the css file?
Below is the part of the code where the styles are involved

const sass = require('gulp-sass')(require('sass'));
const autoprefixer = require('gulp-autoprefixer');
const cleancss = require('gulp-clean-css');
const imagecomp = require('compress-images');
const del = require('del');

function styles() {
  return src('app/sass/style.sass') // Выбираем источник: "app/sass/style.sass"
  .pipe(concat('style.min.css')) // Конкатенируем в файл style.min.js
  .pipe(autoprefixer({ overrideBrowserslist: ['last 10 versions'], grid: true })) // Создадим префиксы с помощью Autoprefixer
  .pipe(cleancss( { level: { 1: { specialComments: 0 } }/* , format: 'beautify' */ } )) // Минифицируем стили
  .pipe(dest('app/css/')) // Выгрузим результат в папку "app/css/"
  .pipe(browserSync.stream()) // Сделаем инъекцию в браузер
}

function buildcopy() {
    return src([
        'app/css/**/*.min.css',
        'app/js/**//*.min.js',
        'app/img/dest/**/*',
        'app/**/*.html',
    ], {base: 'app'})
    .pipe(dest('dist'))
}

function startwatch() {
    watch(['app/**/*.js', '!app/**/*.min.js'], scripts)
    watch('app/sass/**/*', styles);
    watch('app/**/*.html').on('change', browserSync.reload);
}

exports.styles = styles;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-09-08
@delphinpro

function styles() {
  return src('app/sass/style.sсss') // Меняем расширение у файлов
  .pipe(sass()) // Это препроцессор, настройки по умолчанию
//  .pipe(concat('style.min.css')) // Это лишнее
  .pipe(autoprefixer({ overrideBrowserslist: ['last 10 versions'], grid: true })) // Настройки браузеров лучше задавать через файл .browserlistrc
  .pipe(cleancss( { level: { 1: { specialComments: 0 } }/* , format: 'beautify' */ } ))
  .pipe(dest('app/css/'))
  .pipe(browserSync.stream())
}

Here's more for you
simple build example

gulpfile.js
import path from 'path';
import fs from 'fs';
import gulp from 'gulp';
import sass from 'sass';
import browserSync from 'browser-sync';
import twig from 'gulp-twig';
import data from 'gulp-data';
import gulpSass from 'gulp-sass';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'gulp-autoprefixer';

const sassCompiler = gulpSass(sass);

if (!process.env.NODE_ENV) process.env.NODE_ENV = 'production';
console.log('NODE_ENV: ', process.env.NODE_ENV);

const IS_PRODUCTION = process.env.NODE_ENV === 'production';

const bs = browserSync.create();
const __dirname = process.cwd();

const loadData = function () {
    const dataPath = path.resolve(__dirname, 'src/templates/data/main.json');
    let customData = {};

    if (fs.existsSync(dataPath)) {
        customData = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
    } else {
        console.warn('Data file NOT FOUND: ' + dataPath);
    }

    return {
        ...customData,
    };
};

export default function (done) {
    gulp.series(
        build,
        gulp.parallel(
            watch,
            serve,
        ),
    )(done);
}

export function build(done) {
    gulp.parallel(
        copy_scripts,
        copy_images,
        copy_fonts,
        build_twig,
        build_vendor_styles,
        build_styles,
        build_scripts,
    )(done);
}

function serve() {
    bs.init({
        browser: ['chrome'],
        server : {
            baseDir: './dist',
        },
    });
}

function watch() {
    gulp.watch(['./src/templates/**'], build_twig);
    gulp.watch(['./src/scss/**'], build_styles);
    gulp.watch(['./src/js/**'], build_scripts);
    gulp.watch(['./src/img/**'], copy_images);
    gulp.watch(['./src/fonts/**'], copy_fonts);
}

export function build_twig() {
    console.log(path.resolve(__dirname, 'src/templates'));
    return gulp.src('./src/templates/*.twig')
        .pipe(data(loadData))
        .pipe(twig({
            base: path.resolve(__dirname, 'src/templates'),
        }))
        .pipe(gulp.dest('./dist'))
        .on('end', function () {
            bs.reload();
        });
}

export function build_styles() {
    return gulp.src('./src/scss/main.scss')
        .pipe(sourcemaps.init())
        .pipe(sassCompiler({
            outputStyle: IS_PRODUCTION ? 'compressed' : 'expanded',
        }).on('error', sassCompiler.logError))
        .pipe(autoprefixer())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/design/css'))
        .pipe(bs.stream());
}

export function build_vendor_styles() {
    return gulp.src('./src/scss/bootstrap.scss')
        .pipe(sourcemaps.init())
        .pipe(sassCompiler({
            outputStyle: IS_PRODUCTION ? 'compressed' : 'expanded',
        }).on('error', sassCompiler.logError))
        .pipe(autoprefixer())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/design/css'))
        .pipe(bs.stream());
}

export function build_scripts() {
    return gulp.src('./src/js/*.js')
        .pipe(gulp.dest('./dist/design/js'))
        .pipe(bs.stream());
}

export function copy_images() {
    return gulp.src('./src/img/**/*.*')
        .pipe(gulp.dest('./dist/design/img'))
        .on('end', function () {
            bs.reload();
        });
}

export function copy_fonts() {
    return gulp.src('./src/fonts/**/*.*')
        .pipe(gulp.dest('./dist/design/fonts'))
        .on('end', function () {
            bs.reload();
        });
}

export function copy_scripts() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/jquery/dist/jquery.min.map',
        'node_modules/bootstrap/dist/js/bootstrap.min.js',
        'node_modules/bootstrap/dist/js/bootstrap.min.js.map',
    ])
        .pipe(gulp.dest('./dist/design/js'));
}

package.json
{
  "private": true,
  "type": "module",
  "name": "site-ru",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "gulp default"
  },
  "author": "delphinpro <[email protected]>",
  "license": "MIT",
  "dependencies": {
    "@popperjs/core": "^2.9.3",
    "bootstrap": "^5.1.0",
    "jquery": "^3.6.0"
  },
  "devDependencies": {
    "browser-sync": "^2.27.5",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^8.0.0",
    "gulp-data": "^1.3.1",
    "gulp-sass": "^5.0.0",
    "gulp-sourcemaps": "^3.0.0",
    "gulp-twig": "^1.2.0",
    "sass": "^1.38.2"
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question