This example watches a folder containing LESS files and compiles them to CSS on any changes or when the project is built or cleaned.
By doing this you can have a primary LESS file, and when this or any referenced by it through “@import” statements, compiling to a single CSS file.
In this example, the primary LESS file is called “main.less”, it will be compiled to “main.css” and “main.min.css”.
///var gulp = require('gulp'); var concat = require('gulp-concat'); var less = require('gulp-less'); var minifyCss = require('gulp-minify-css'); var rename = require("gulp-rename"); var watch = require('gulp-watch'); var del = require('delete'); var sass = require('gulp-ruby-sass') var notify = require("gulp-notify") var bower = require('gulp-bower'); var MainConfig = { watch: ['main/**/*.less'], //folder to watch for changes src: ['main/main.less'], //main LESS file to compile targetDir: '../target-folder/css', //folder to output compiled CSS targetName: 'main', //name of compiled CSS file targetMinName: 'main.min' //name of minified CSS file } function BuildMain() { gulp.src(MainConfig.src) .pipe(less()) .on('error', swallowError) .pipe(gulp.dest(MainConfig.targetDir)) .pipe(minifyCss()) .on('error', swallowError) .pipe(rename({ basename: MainConfig.targetMinName, extname: ".css" })) .pipe(gulp.dest(MainConfig.targetDir)); //If theres an error generating the css, delete the existing css files function swallowError(error) { var _cssName = MainConfig.targetDir + "/" + MainConfig.targetName + ".css"; var _cssMinName = MainConfig.targetDir + "/" + MainConfig.targetMinName + ".css"; del.sync(_cssName, { force: true }); del.sync(_cssMinName, { force: true }); this.emit('end'); } } //Tasks to be used by Task Runner gulp.task('project-start', function () { watch(MainConfig.watch, function () { BuildMain(); }); }); gulp.task('project-clean', function () { BuildMain(); }); gulp.task('project-build', function () { BuildMain(); });
The script is saved as “gulpfile.js” in the root of the project
No comments:
Post a Comment