I have this code:
var gulp = require('gulp'),
rename = require('gulp-rename'),
less = require('gulp-less'),
path = require('path'),
cleanCSS = require('gulp-clean-css'),
uglify = require('gulp-uglify');
const { watch, series, task } = require('gulp');
task('uglify', async function () {
gulp.src('assets/js/*.js')
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('assets/public/js/'))
});
task('less', function () {
return gulp.src('assets/less/*.less')
.pipe(less({
paths: [ path.join(__dirname, 'less', 'fragments') ]
}))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('assets/public/css/'));
});
task('default', series('uglify', 'less'));
/* task('default', function (){
watch('assets/less/*.less', series(less));
watch('assets/js/*.js', series(uglify));
return;
}); */
When I run the initial code, the first default, gulp works correctly and compresses my files successfully. However, when I change it to the one that has the watchers, it doesn't react to the changes, only this appears in the console:
16:02:09] Starting 'default'...
16:02:59] Starting ''...
Whay can I do?
Related
I'm working on an old project which is using Gulp.
I had to update gulp v3 to v4 and this is how it looks like:
var gulp = require('gulp')
var sass = require('gulp-sass')
var sourcemaps = require('gulp-sourcemaps')
var browserSync = require('browser-sync').create()
var uglify = require('gulp-uglify')
var concat = require('gulp-concat')
var notify = require('gulp-notify')
var series = require('stream-series') // Helps to concat js files in desired order
// BrowserSync task
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: './'
}
})
})
// Style task
gulp.task('sass', function () {
return gulp.src('./src/sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
errLogToConsole: true,
outputStyle: 'compressed'
}))
.pipe(concat('style.min.css'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Styles task complete' }))
})
// Script task
gulp.task('script', function () {
return series(
gulp.src('./src/js/vendor/**/*.js'),
gulp.src('./src/js/modules/**/*.js')
)
.pipe(concat('bundle.js'))
.pipe(uglify())
.pipe(gulp.dest('./js'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Script task complete' }))
})
// watch task
gulp.task('watch', gulp.series('sass', 'script', 'browserSync'), function () {
gulp.watch('./src/sass/**/*.scss', ['sass'])
gulp.watch('./src/js/**/*.js', ['script'])
gulp.watch('./index.html', browserSync.reload)
})
If I run gulp watch it compiles all sass and JS files and shows the page in browser correctly.
But after that it doesn't watch anymore and if I change any sass or JS files, those changes are not applied.
What is wrong with my gulp script?
I managed to fix it myself.
const gulp = require('gulp')
const sass = require('gulp-sass')
const sourcemaps = require('gulp-sourcemaps')
const browserSync = require('browser-sync').create()
const uglify = require('gulp-uglify')
const concat = require('gulp-concat')
const notify = require('gulp-notify')
const series = require('stream-series') // Helps to concat js files in desired order
// HTML task
function html () {
return gulp.src('./*.html')
.pipe(gulp.dest('./build'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'HTML task complete' }))
}
// Style task
function style () {
return gulp.src('./src/sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
errLogToConsole: true,
outputStyle: 'compressed'
}))
.pipe(concat('style.min.css'))
// .pipe(cssmin())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./build/css'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Styles task complete' }))
}
// Script task
function script () {
// return gulp.src('./src/js/**/*.js')
return series( // concats js files in desired order
gulp.src('./src/js/vendor/**/*.js'),
gulp.src('./src/js/modules/**/*.js')
)
.pipe(concat('bundle.js'))
.pipe(uglify())
.pipe(gulp.dest('./build/js'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Script task complete' }))
}
function watch () {
html()
style()
script()
browserSync.init({
server: {
baseDir: './build'
}
})
gulp.watch('./*.html', html).on('change', browserSync.reload)
gulp.watch('./src/sass/**/*.scss', style).on('change', browserSync.reload)
gulp.watch('./src/js/**/*.js', script).on('change', browserSync.reload)
}
exports.html = html
exports.style = style
exports.script = script
exports.watch = watch
please let me know if you have any suggestion to improve my solution.
I have a Jekyll site which uses Gulp to compile the Jekyll files amongst other tasks such as compiling my sass, js files and running Browsersync. I'm migrating to Gulp 4.0 so have been updating my gulpfile.js to reflect this...however when I run 'gulp' in command line and update a Jekyll file, the build now loops infinitely. This only happens when I update a Jekyll file or a js file, not when I update a sass file. Here is my code:
var gulp = require('gulp'),
browserSync = require('browser-sync').create(),
sass = require('gulp-sass'),
babel = require('gulp-babel'),
autoprefixer = require('gulp-autoprefixer'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
svgmin = require('gulp-svgmin'),
sourcemaps = require('gulp-sourcemaps'),
cp = require('child_process'),
jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
// =======================================================================
// Browser Sync
// =======================================================================
gulp.task('browser-sync', function(done)
{
browserSync.init({
server: {
baseDir: "_site"
},
port: 3004,
open: false
});
done();
});
gulp.task('browser-sync-reload', function(done)
{
browserSync.reload();
done();
});
// =======================================================================
// SASS
// =======================================================================
var sassOptions = {
includePaths: ['scss'],
errLogToConsole: true,
outputStyle: 'compressed',
//sourceComments: 'map'
};
//Auto prefixer options
var autoPrefixerOptions = {
browsers: ['last 15 versions', '> 1%', 'ie 8', 'ie 7']
};
var styleInput = [
'_sass/**/_*.scss',
'_sass/site.scss'
];
gulp.task('sass-style', function()
{
return gulp.src(styleInput)
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer(autoPrefixerOptions, { cascade: true }))
.pipe(rename('styles.css'))
.pipe(gulp.dest('_site/css'))
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
});
// =======================================================================
// JS
// =======================================================================
var jsInput = [
'js/libs/**/*.js',
'js/site.js'
];
//Compile js to older browser compatible output
gulp.task('babel-js-min', function() {
return gulp.src(jsInput)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(concat('site.js'))
.pipe(uglify())
.pipe(rename('scripts.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_site/js/dist'))
.pipe(gulp.dest('js/dist'))
.pipe(browserSync.stream());
});
//Compile js to older browser compatible output
gulp.task('babel-js', function() {
return gulp.src(jsInput)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(concat('site.js'))
.pipe(rename('scripts.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_site/js/dist'))
.pipe(gulp.dest('js/dist'))
.pipe(browserSync.stream());
});
// =======================================================================
// SVGs
// =======================================================================
function onError(error)
{
console.log(error);
this.emit('end');
}
var svgInput = [
'_includes/svgs/src/**/*'
];
gulp.task('svgmin', function()
{
return gulp.src(svgInput)
.pipe(svgmin())
.on('error', onError)
.pipe(gulp.dest('./_includes/svgs/dist'));
});
// =======================================================================
// Jekyll
// =======================================================================
var jekyllFiles = [
'_includes/*.html',
'_layouts/*.html',
'**/*.md'
];
gulp.task('jekyll-build', function(done)
{
return cp.spawn("bundle", ["exec", "jekyll", "build"], { stdio: "inherit" }).on('close', done);
});
// =======================================================================
// Watch
// =======================================================================
gulp.task('watch', function()
{
gulp.watch(styleInput, gulp.series('sass-style'));
gulp.watch(jsInput, gulp.series('babel-js-min'));
gulp.watch(jsInput, gulp.series('babel-js'));
gulp.watch(svgInput, gulp.series('svgmin'));
gulp.watch(jekyllFiles, gulp.series('jekyll-build', 'browser-sync-reload'));
});
// =======================================================================
// Define the default task and add the watch task to it
// =======================================================================
gulp.task('default', gulp.parallel('watch', 'browser-sync'));
Any help with this would be appreciated.
I figured this out for anyone that has the same issue...my Jekyll child process was causing the infinite loop (only when editing a Jekyll file). Updating it to the following did the trick:
return cp.spawn(jekyll, ['build', '--incremental', '--drafts'], {stdio: "inherit"}).on('close', done);
I'm studying GULP, and I want the page to update automatically when I modify the CSS.
const gulp = require("gulp");
const jshint = require("gulp-jshint");
const changed = require("gulp-changed");
const watch = require("gulp-watch");
const rename = require("gulp-rename");
const minifyCSS = require("gulp-uglifycss");
const sass = require("gulp-sass");
const cssImport = require("gulp-cssimport");
gulp.task("changed", function() {
return gulp
.src("src/css/*.css")
.pipe(changed("public/assets/css/"))
.pipe(cssImport())
.pipe(sass())
.pipe(minifyCSS())
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("public/assets/css/"));
});
gulp.task("jshint", function() {
gulp
.src("src/css/*.css")
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("watch", function() {
watch("src/css/*.css", ["changed"]);
});
gulp.task("default", ["jshint", "watch"]);
I'm trying to use "gulp-watch", but it's giving the error "Task function must be specified" in this code above.
The problem was that I was trying to watch the old version of GULP, not version 4.0.0.
So I changed my code to work, and it looked like this:
const gulp = require("gulp");
const rename = require("gulp-rename");
const minifyJS = require("gulp-uglify");
const minifyCSS = require("gulp-uglifycss");
const sass = require("gulp-sass");
const babel = require("gulp-babel");
const cssImport = require("gulp-cssimport");
gulp.task(
"base",
gulp.series(function() {
return gulp.src("src/templates/*.html").pipe(gulp.dest("public/"));
})
);
gulp.task(
"javascript",
gulp.series(function() {
return gulp
.src("src/js/*.js")
.pipe(babel({ presets: ["#babel/env"] }))
.pipe(minifyJS())
.pipe(rename({ extname: ".min.js" }))
.pipe(gulp.dest("public/assets/js/"));
})
);
gulp.task(
"css",
gulp.series(function() {
return gulp
.src("src/css/*.css")
.pipe(cssImport())
.pipe(sass())
.pipe(minifyCSS())
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("public/assets/css/"));
})
);
gulp.task(
"watch",
gulp.series(function() {
gulp.watch("src/templates/*.html", gulp.parallel(["base"]));
gulp.watch("src/js/*.js", gulp.parallel(["javascript"]));
gulp.watch("src/css/*.css", gulp.parallel(["css"]));
})
);
gulp.task(
"default",
gulp.series(gulp.parallel("base", "javascript", "css", "watch"))
);
I'm working with a small project using gulp and I want to learn about vue.js, so I want to use vue.js in this project, but I don't know how to configure vue.js in the gulpfile.js
I want to know how to configure gulpfile to use vue.js
My gulpfile.js
var env = require('minimist')(process.argv.slice(2)),
gulp = require('gulp'),
gutil = require('gulp-util'),
plumber = require('gulp-plumber'),
jade = require('gulp-jade'),
browserify = require('gulp-browserify'),
browserSync = require('browser-sync'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpif = require('gulp-if'),
stylus = require('gulp-stylus'),
jeet = require('jeet'),
rupture = require('rupture'),
koutoSwiss = require('kouto-swiss'),
prefixer = require('autoprefixer-stylus'),
modRewrite = require('connect-modrewrite'),
imagemin = require('gulp-imagemin'),
karma = require('gulp-karma'),
cache = require('gulp-cache'),
rsync = require('rsyncwrapper').rsync;
// Call Jade for compile Templates
gulp.task('jade', function () {
return gulp.src('src/templates/*.jade')
.pipe(plumber())
.pipe(jade({pretty: !env.p}))
.pipe(gulp.dest('build/'));
});
gulp.task('copy', function() {
return gulp.src(['src/*.html', 'src/*.txt'])
.pipe(gulp.dest('build/'))
});
// Call Uglify and Concat JS
gulp.task('js', function () {
return gulp.src('src/js/**/*.js')
.pipe(plumber())
.pipe(concat('main.js'))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
// Call Uglify and Concat JS
gulp.task('browserify', function () {
return gulp.src('src/js/main.js')
.pipe(plumber())
.pipe(browserify({debug: !env.p}))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
// Call Stylus
gulp.task('stylus', function () {
gulp.src('src/styl/main.styl')
.pipe(plumber())
.pipe(stylus({
use:[koutoSwiss(), prefixer(), jeet(), rupture()],
compress: env.p,
}))
.pipe(gulp.dest('build/css'));
});
// Call Imagemin
gulp.task('imagemin', function () {
return gulp.src('src/img/**/*')
.pipe(plumber())
.pipe(cache(imagemin({optimizationLevel: 3, progressive: true, interlaced: true})))
.pipe(gulp.dest('build/img'));
});
// Call Watch
gulp.task('watch', function () {
gulp.watch('src/templates/**/*.jade', ['jade']);
gulp.watch('src/styl/**/*.styl', ['stylus']);
gulp.watch('src/js/**/*.js', [(env.fy) ? 'browserify' : 'js']);
gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
});
gulp.task('browser-sync', function () {
var files = [
'build/**/*.html',
'build/css/**/*.css',
'build/img/**/*',
'build/js/**/*.js',
];
browserSync.init(files, {
server: {
baseDir: './build/',
},
});
});
// Rsync
gulp.task('deploy', function () {
rsync({
ssh: true,
src: './build/',
dest: 'user#hostname:/path/to/www',
recursive: true,
syncDest: true,
args: ['--verbose'],
},
function (erro, stdout, stderr, cmd) {
gutil.log(stdout);
});
});
// Default task
gulp.task('default', [(env.fy) ? 'browserify' : 'js', 'jade', 'copy', 'stylus', 'imagemin', 'watch', 'browser-sync']);
// Build and Deploy
gulp.task('build', [(env.fy) ? 'browserify' : 'js', 'jade', 'copy', 'stylus', 'imagemin', 'deploy']);
Vueify is a browserify transform; gulp-browserify isn't maintained anymore but I assume that you can still add vueify as a transform once it's installed:
gulp.task('browserify', function () {
return gulp.src('src/js/main.js')
.pipe(plumber())
.pipe(browserify({
debug: !env.p,
transform: ['vueify']
}))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
Check this out:
This is a package which lets you setup gulp task for vue.js.
https://www.npmjs.com/package/gulp-vueify
Using:
.pipe(babel({presets: ['es2015']}))
On a normal gulp task helped me concat and uglify my vue.js files.
If this is what you meant, then you will also need to install babel with npm and add:
var babel = require('gulp-babel');
I got this Gulp file where I'm running various tasks.
I would like to delete the contents of my build directory before running any other tasks but can't work out how to do this.
I've tried lots of various ways I found when searching for a solution to this but can't get it to work.
Here is my Gulp file:
// List required plugins
var gulp = require('gulp'),
del = require('del'),
uglify = require('gulp-uglify'),
postcss = require('gulp-postcss'),
lost = require('lost'),
nano = require('gulp-cssnano'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('autoprefixer'),
mqpacker = require('css-mqpacker'),
mixins = require('postcss-mixins'), // Must go before other plugins in the PostCSS task
nested = require('postcss-nested'),
vars = require('postcss-simple-vars'),
partials = require('postcss-import'),
plumber = require('gulp-plumber'),
gutil = require('gulp-util'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
browserSync = require('browser-sync').create();
// Config - Paths and other config
var src = {
cssDir: 'src/css/**/*.css',
jsDir: 'src/js/**/*.js',
imgDir: 'src/img/*',
svgDir: 'src/img/svg/**/*.svg',
htmlDir: 'src/**/*.html',
srcDir: 'src/',
},
build = {
buildDir: 'build/',
cssDir: 'build/assets/css/',
htmlDir: 'build/**/*.html',
jsDir: 'build/assets/js/',
imgDir: 'build/assets/img/',
},
options = {
autoprefix: { browsers: ['last 2 versions'] },
imagemin: { optimizationLevel: 7, progressive: true, interlaced: true, svgoPlugins: [ {removeViewBox: false}, {cleanupIDs: false} ], use: [pngquant()] },
port: '80',
};
// Error handling function
// Thanks to https://cameronspear.com/blog/how-to-handle-gulp-watch-errors-with-plumber/
var onError = function(err) {
gutil.beep();
console.log(err);
this.emit('end');
}
// Clean task
gulp.task('clean:build', function () {
return del([
build.buildDir,
]);
});
// Copy HTML to Build
gulp.task('html', function () {
return gulp.src(src.htmlDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(gulp.dest(build.buildDir))
.pipe(browserSync.stream());
});
// BrowserSync Server + watching files for changes
gulp.task('server', function() {
browserSync.init({
server: {
baseDir: build.buildDir
},
port: options.port,
});
});
// PostCSS Task
gulp.task('css', function () {
var processors = [
partials(),
lost(),
autoprefixer({ browsers: ['last 2 version'] }),
mixins(),
nested(),
vars(),
mqpacker(), // Make sure mqpacker is last!
];
return gulp.src(src.cssDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(postcss(processors))
//.pipe(nano()) - Disable minification during development
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(build.cssDir))
.pipe(browserSync.stream());
});
// JS Task
gulp.task('compressJS', function() {
return gulp.src(src.jsDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(uglify())
.pipe(gulp.dest(build.jsDir))
.pipe(browserSync.stream());
});
// Image Task
gulp.task('imagemin', function() {
return gulp.src(src.imgDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(imagemin(
options.imagemin
))
.pipe(gulp.dest(build.imgDir))
.pipe(browserSync.stream());
});
gulp.task('watch', function () {
gulp.watch(src.cssDir, ['css']);
gulp.watch(src.jsDir, ['compressJS']);
gulp.watch(src.htmlDir, ['html']);
gulp.watch(src.imgDir, ['imagemin']);
});
gulp.task('default', ['html', 'imagemin', 'compressJS', 'server', 'watch']);
How should I do to run the task clean:build before any other tasks but only run it once. Or is there a better way of cleaning out files before running a build?
Thanks!!
Have your tasks depend on your clean task:
gulp.task('html', ['clean:build'], function() { ... })
this is how i do it.
var del = require('del') ;
gulp.task('delete-build-folder', function(cb) {
return del([config.buildDir], cb);
});
gulp.task('default', ['delete-build-folder'], function() {
console.log('building.....');
gulp.start('copy-html', 'copy-html-views');
});