πΊπ¦Ukraine Oleksandr Zharskyi
Gulpfile for Node.js 20 version, ESM6 JavaScript, 2024
// You need to change the gulpfile.js extension to gulpfile.mjs. The sample code is below:
import * as sass from 'sass';
import gulp from 'gulp';
import gulpSass from 'gulp-sass';
import rename from 'gulp-rename';
import autoprefixer from 'gulp-autoprefixer';
import cleancss from 'gulp-clean-css';
import sourcemaps from 'gulp-sourcemaps';
import concat from 'gulp-concat';
import uglify from 'gulp-uglify';
import livereload from 'gulp-livereload';
livereload({ start: true });
const syntax = 'scss'; // Syntax: sass or scss;
const paths = {
styles: {
src: `./${syntax}/**/*.${syntax}`,
dest: './css'
},
scripts: {
src: './libs/**/*.js',
dest: './js'
},
twig: {
src: './**/*.html.twig'
}
};
const sassCompiler = gulpSass(sass);
// Task for compiling stylesheets
gulp.task('styles', function () {
return gulp.src(paths.styles.src) // Select source files
.pipe(sourcemaps.init()) // Initialize sourcemaps
.pipe(sassCompiler.sync({outputStyle: 'compressed'}).on('error', sassCompiler.logError)) // Compile Sass to CSS, minify, and handle errors
.pipe(rename({ suffix: '.min', prefix : '' })) // Rename the output file
.pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true, grid: true })) // Add vendor prefixes
.pipe(cleancss( {level: { 1: { specialComments: 0 } } })) // Optimize CSS
.pipe(sourcemaps.write('./')) // Write sourcemaps
.pipe(gulp.dest(paths.styles.dest)) // Output compiled CSS
.pipe(livereload()); // Reload the browser
});
// Task for concatenating and minifying JavaScript files
gulp.task('scripts', function () {
return gulp.src(paths.scripts.src) // Select source files
.pipe(concat('common.min.js')) // Concatenate all scripts into one file
.pipe(uglify().on('error', function(err){ // Minify JavaScript, handle errors
console.error(err.toString());
this.emit('end');
}))
.pipe(gulp.dest(paths.scripts.dest)) // Output minified script
.pipe(livereload()); // Reload the browser
});
// Task for watching file changes and triggering appropriate tasks
gulp.task('watch', function () {
livereload.listen(); // Start livereload server
// Watch for changes in stylesheets, scripts, and Twig templates
gulp.watch(paths.styles.src, gulp.parallel('styles'));
gulp.watch(paths.scripts.src, gulp.parallel('scripts'));
gulp.watch(paths.twig.src, gulp.parallel('twig'));
});
// Task for reloading Twig templates
gulp.task('twig', function () {
return gulp.src(paths.twig.src) // Select Twig templates
.pipe(livereload()); // Reload the browser
});
// Default task to run all tasks in parallel
gulp.task('default', gulp.parallel('styles', 'scripts', 'twig', 'watch'));
πΊπ¦Ukraine Oleksandr Zharskyi
+