I am trying to add a couple of gulp tasks. I have a basic HTML site that I want to watch changes for and reload with updated changes. I am trying to use livereload to listen and changed. however when it reloads i get an error that the Port is already in use which makes sense. But I cannot find a solution. First time to use Gulp so any tips on making what I have done better is welcome
var gulp = require('gulp');
var livereload = require('gulp-livereload');
var rev = require('gulp-rev');
var clean = require('gulp-rimraf');
var runSequence = require('run-sequence').use(gulp);
var connect = require('gulp-connect');
gulp.task('build', function () {
// by default, gulp would pick `assets/css` as the base,
// so we need to set it explicitly:
return gulp.src(['assets/css/*.css','assets/css/**/*.css', 'assets/js/*.js', 'assets/js/**/*.js', 'assets/js/**/**/*.js', 'assets/img/**/*.jpg', 'assets/img/**/*.png'], { base: 'assets' })
.pipe(gulp.dest('build/assets')) // copy original assets to build dir
.pipe(rev())
.pipe(gulp.dest('build/assets')) // write rev'd assets to build dir
.pipe(rev.manifest())
.pipe(gulp.dest('build/assets')); // write manifest to build dir
});
gulp.task('copy', function () {
gulp.src('index.html')
.pipe(gulp.dest('build'));
gulp.src('assets/fonts/*.*')
.pipe(gulp.dest('build/assets/fonts'));
gulp.src('assets/fonts/revicons/*.*')
.pipe(gulp.dest('build/assets/fonts/revicons'));
});
gulp.task('clean', [], function() {
return gulp.src("build/*", { read: false }).pipe(clean());
});
gulp.task('watch', function () {
livereload.listen(35729, function(err) {
if(err) return console.log(err);
})
gulp.watch(['index.html', 'assets/css/*.css','assets/css/**/*.css', 'assets/js/*.js', 'assets/js/**/*.js', 'assets/js/**/**/*.js', 'assets/img/**/*.jpg', 'assets/img/**/*.png'], [], function (e) {
livereload.changed(e.path, 35729)
});
});
gulp.task('connect', function() {
connect.server({
host: '0.0.0.0',
root: 'build',
port: 8000,
livereload: true
});
});
gulp.task('default', function() {
runSequence(
'dist',
['connect', 'watch']
);
});
gulp.task('dist', ['clean'], function () {
gulp.start('build');
gulp.start('copy');
});
You may want to check on your host if any process has been running on port - 35729. You can kill that process and try to rerun this application. Find and kill process
or
you can try with different port number than 35729 in your code.
Hope this would help.
Related
We are switching from gulp#3.9.1 to gulp#4 and are having trouble switching over. When we run gulp watch, we are getting the following errors and trying to figure out how to resolve it.
What is the proper way to convert the gulp watch task to work with gulp#4?
Error message
AssertionError [ERR_ASSERTION]: Task never defined: minify-css
Command: gulp watch
This should run minify-js then minify-css in order
minify-js should run after clean-scripts has completed successfully
minify-css should run after clean-css has completed successfully
Current tasks.
var gulp = require('gulp'),
cssmin = require('gulp-clean-css'),
clean = require('gulp-clean'),
uglify = require('gulp-uglify');
var src = {
js: 'js/some-dir/**/*.js',
css: 'css/some-dir/**/*.css'
};
var dest = {
js: 'js/dest/some-dir/**/*.js',
css: 'css/dest/some-dir/**/*.css'
};
gulp.task('clean-css', function() {
return gulp.src(dest.css)
.pipe(clean({read:false, force: true});
});
gulp.task('minify-css', ['clean-css'], function() {
gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
});
gulp.task('clean-scripts', function() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
});
gulp.task('minify-js', ['clean-scripts'], function() {
gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
});
gulp.task('watch', ['minify-js', 'minify-css'], function() {
gulp.watch(src.js, ['minify-js']);
gulp.watch(src.css, ['minify-css']);
});
We tried doing this, but it resulted in the error message
gulp.task('watch', gulp.series('minify-js', 'minify-css', function() {
gulp.watch(src.js, ['minify-js']);
gulp.watch(src.css, ['minify-css']);
}));
gulp.task('minify-css', gulp.series('clean-css', function() {
return gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
}));
gulp.task('minify-js', gulp.series('clean-scripts', function() {
return gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
}));
gulp.task('watch', gulp.series('minify-js', 'minify-css', function() {
gulp.watch(src.js, gulp.series('minify-js'));
gulp.watch(src.css, gulp.series('minify-css'));
}));
As #Abdaylan suggested, I also advocate switching to functions. Nevertheless, so you can see where your code was wrong, I have fixed it here. Gulp 4 does not use this syntax:
gulp.task('someTask', ['task1', 'task2'], function () {}); // gulp 3
Gulp 4:
gulp.task('someTask', gulp.series('task1', 'task2', function () {})); // gulp 4 with string tasks
or gulp.parallel. So you can use your gulp.task syntax (rather than named functions) if you modify them to use the signatures that gulp 4 supports as I did in your modified code at the top of this answer.
Gulp 4 with named functions:
gulp.task(someTask, gulp.series(task1, task2, function () {})); // gulp 4 with named functions
So with named functions, the tasks are not referred to as strings.
See also task never defined for other potential problems when migrating from gulp3 to gulp4 with the same error message.
I would recommend converting your minify-js, minify-css, clean-scripts and clean-css tasks to functions:
var dest = {
js: 'js/dest/some-dir/**/*.js',
css: 'css/dest/some-dir/**/*.css'
};
function cleanCss() {
return gulp.src(dest.css)
.pipe(clean({read:false, force: true});
});
function minifyCss() {
return gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
});
function cleanScripts() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
});
function minifyJs() {
return gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
});
var minifyJsAndClean = gulp.series(minifyJs, cleanScripts);
var minifyCssAndClean = gulp.series(minifyCss, cleanCss);
var watchers = function (done) {
gulp.watch(src.js, minifyJs);
gulp.watch(src.css, minifyCss);
done();
}
gulp.task('watch', gulp.series(minifyJsAndClean, minifyCssAndClean, watchers));
I just ran into this a couple days ago myself. What worked for me was to run each task in its own gulp.watch() with the gulp.series() on the watch task call instead of the watch task itself. For example:
gulp.task('watch', function() {
gulp.watch(src.js, gulp.series('minify-js'));
gulp.watch(src.css, gulp.series('minify-css'));
});
I've spent the whole day trying to figure this out right. I am aware of
Gulp 4 & BrowserSync: Style Injection?
and tried different approaches to this. What am I missing?
I am trying to get gulp to inject the sass generated style to the browser. As of now, it does open a new tab with the generated css, but it does neither refresh nor inject the newly generated style when changing. I get:
[Browsersync] Watching files...
[21:27:36] Starting 'buildStyles'...
[21:27:36] Finished 'buildStyles' after 40 ms
[Browsersync] File event [change] : site/templates/styles/main.css
But it doesn't inject. Here's my gulpfile.js:
const { src, dest, watch, series, parallel } = require('gulp');
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const paths = {
sass: {
// By using styles/**/*.sass we're telling gulp to check all folders for any sass file
src: "site/templates/styles/scss/*.scss",
// Compiled files will end up in whichever folder it's found in (partials are not compiled)
dest: "site/templates/styles"
},
css: {
src: "site/templates/styles/main.css"
}
};
function buildStyles(){
return src(paths.sass.src)
.pipe(sass())
.on("error", sass.logError)
.pipe(dest(paths.sass.dest))
}
function watchFiles(){
watch(paths.sass.src,{ events: 'all', ignoreInitial: false }, series(buildStyles));
}
function browserSync(done){
browsersync.init({
injectChanges: true,
proxy: "http://client2019.local/",
port: 8000,
host: 'client2019.local',
socket: {
domain: 'localhost:80'
},
files: [
paths.css.src
]
});
done();
// gulp.watch("./**/*.php").on("change", browserSync.reload);
}
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles;
exports.watch = watchFiles;
exports.build = series(buildStyles); // $ gulp build
What am I missing?
I don't know if I fully understand what are you want.
To auto refresh the browser with BrowserSync, after saving your last changes, I'm using this code on my gulp file:
var paths = {
styles: {
src: "./src/styles/scss/**/*.scss",
dest: "./view/styles"
},
htmls: {
src: "./src/**/*.html",
dest: "./view"
}
};
const styles= () => {
return...
}
const html= () => {
return...
}
const watch = () => {
browserSync.init({
server: {
baseDir: "./view"
}
});
gulp.watch(paths.styles.src, style);
gulp.watch(paths.htmls.src, html);
gulp.watch("src/**/*.html").on('change', browserSync.reload);
};
exports.style = style;
exports.html = html;
exports.watch = watch;
var build = gulp.parallel(style, html, watch);
gulp.task('default', working);
Then I just execute gulp for build and watch with auto reload.
I've installed gulp-livereload to reload pages after making changes in .js files.
Here is the code:
const gulp = require('gulp');
const livereload = require('gulp-livereload');
gulp.task('jsLiveReload', () => {
gulp
.src('/home/ksdmwms/Desktop/projs/others/tests/gulp_test/src/js/file.js')
.pipe(livereload());
});
gulp.task('watchJsTest', function() {
livereload.listen({
reloadPage: 'http://localhost/projs/others/tests/gulp_test/src/index.html'
});
gulp.watch('/home/ksdmwms/Desktop/projs/others/tests/gulp_test/src/js/file.js', gulp.series('jsLiveReload'));
});
So its listening changes on file.js.
When i execute i get this:
gulp watchJsTest
[14:05:40] Using gulpfile /opt/lampp/htdocs/projs/others/tests/gulp_test/gulpfile.js
[14:05:40] Starting 'watchJsTest'...
[14:05:46] Starting 'jsLiveReload'...
[14:05:46] /home/ksdmwms/Desktop/projs/others/tests/gulp_test/src/js/file.js reloaded.
It reloads only when i save the first changes, if i make another changes its not reloading.
How can i solve this?
Note: Im using livereload chrome extension and Ubuntu 18.04
If gulp is installed in /home/ksdmwms/Desktop/projs/others/tests/gulp_test
you could try this:
var gulp = require('gulp'),
livereload = require('gulp-livereload');
gulp.task('jsLiveReload', function() {
gulp.src('./src/js/**/*.js')
.pipe(livereload());
//.pipe(gulp.dest(''));
});
gulp.task('watchJsTest', function() {
livereload.listen({
reloadPage: 'http://localhost/'
});
gulp.watch('./src/js/**/*.js', ['jsLiveReload']);
});
Tell me if it works :)
Have you already tried brwosersync?
Browser-sync > Gulp-live-reload
Browser-Sync
const gulp = require('gulp')
const browserSync = require('browser-sync').create()
gulp.task('js', () => {
return gulp.src([
'Files1',
'File2'
])
.pipe(gulp.dest(''))
.pipe(browserSync.stream())
})
gulp.task('serve', ['sass', 'js'], () => {
browserSync.init({
server: './src',
})
gulp.watch([
'src/sass/*.scss',
'src/js/*.js',
], ['sass', 'js'])
gulp.watch('src/*.html').on('change', browserSync.reload)
})
gulp.task('default', ['serve'])
In serve task, gulp.watch
I use Gulp to run Jekyll. My setup works fine on localhost, but when I introduce Github Pages relative links stop working. I use gulp-gh-pages npm package to push _site contents to gh-pages branch.
Contents of gulpfile.js related to Jekyll and Github Pages:
var browserSync = require('browser-sync').create();
var gulp = require('gulp');
var runSequence = require('run-sequence');
var ghPages = require('gulp-gh-pages');
var gutil = require('gulp-util');
var run = require('gulp-run');
var del = require('del');
gulp.task('build:jekyll', function(callback) {
var shellCommand = 'jekyll build --incremental';
return gulp.src('')
.pipe(run(shellCommand))
.on('error', gutil.log);
callback();
});
gulp.task('clean', function() {
return del(['_site', 'assets']);
});
// [`build:scripts`, `build:styles`, `build:images`] is removed from the runSequence example for MVP
gulp.task('build:prod', function(callback) {
return runSequence('clean', 'build:jekyll', callback)
browserSync.reload();
});
gulp.task('deploy',['build:prod'], function(){
return gulp.src('./_site/**/*')
.pipe(ghPages());
});
Contents of config.yml:
baseurl: /
collections:
pages:
output: true
permalink: /:title/
exclude: ["_assets", "gulpfile.js", "node_modules", "package.json", "package-lock.json", ".jekyll-metadata"]
Reference to assets:
<link rel="stylesheet" href="{{ site.baseurl }}assets/styles/main.min.css">
Front matter on every page inside _pages directory:
---
layout: page
title: Title
description: Awesome description
image: https://source.unsplash.com/random/?water
---
Here is the link to my Github repository with full source code: https://github.com/alljamin/portfolio
How can I configure Gulp and Jekyll so all the relative links work both locally and on Github Pages?
Try : "baseurl: /portfolio"
Generate url with {{site.baseurl}}/path/to/res or {{ "/path/to/res" | prepend: site.baseurl }}.
Elaborating on the #david-jacquel answer I was able to find a way to successfully run localhost and Github Pages environments via separate Gulp tasks.
Contents of gulpfile.js:
gulp.task('build:jekyll:dev', function(callback) {
var shellCommand = 'jekyll build --incremental --baseurl "" ';
return gulp.src('')
.pipe(run(shellCommand))
.on('error', gutil.log);
callback();
});
gulp.task('build:jekyll:prod', function(callback) {
var shellCommand = 'jekyll build --incremental';
return gulp.src('')
.pipe(run(shellCommand))
.on('error', gutil.log);
callback();
});
The build:jekyll:dev task will overwrite the _config.yml baseurl to "". So I can do something like this:
gulp.task('build:dev', function(callback) {
return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:dev', callback)
browserSync.reload();
});
gulp.task('build:prod', function(callback) {
return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:prod', callback)
browserSync.reload();
});
gulp.task('serve', ['build:dev'], function() {
browserSync.init({
server: {
baseDir: "_site"
},
ghostMode: false,
logFileChanges: true,
logLevel: 'debug',
open: true
});
gulp.watch(...);
});
gulp.task('deploy',['build:prod'], function(){
return gulp.src('./_site/**/*')
.pipe(ghPages());
});
I'm new to gulp and I've got a couple of gulp questions that I hope are pretty easy (meaning I'll probably have one of those forehead smacking moments when I hear the answer)...
My gulpfile has a number of repetitive one-way copy tasks, and then I'm watching these separate tasks in the watch command, however I'm almost certain that the way I'm doing it is totally inefficient.
Also, I'm noticing some interesting behavior, the copy command for syncHtmlRootDir task works exactly as I hoped (it will delete files as necessary), but none of my other one way copy tasks will remove deleted files, and I'm guessing it's a pathing issue, but I'm stumped on it.
gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css')
var uglify = require('gulp-uglify');
var newer = require('gulp-newer');
var path = require('path');
var del = require('del');
function handleError (error) {
console.log(error.toString())
this.emit('end')
}
//setup browerSync to serve from both src and dist directories.
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: ["./", "src"] // ./ signifies root of folder, allows to load files from dist and src folders.
},
})
});
//one way sync of root folder
gulp.task('syncHtmlRootDir', function(done) {
return gulp.src(['src/*.html'])
.pipe(newer('dist/'))
.pipe(gulp.dest('dist/'))
.pipe(browserSync.reload({
stream: true
}))
});
//one way sync of app folder
gulp.task('syncHtmlAppDir', function(done) {
return gulp.src(['src/app/**/*'])
.pipe(newer('dist/app/'))
.pipe(gulp.dest('dist/app/'))
.pipe(browserSync.reload({
stream: true
}))
});
//one way sync of image folder
gulp.task('syncImgDir', function(done) {
return gulp.src(['src/assets/img/**/*'])
.pipe(newer('dist/assets/img/'))
.pipe(gulp.dest('dist/assets/img/'))
.pipe(browserSync.reload({
stream: true
}))
});
//copy and compile SCSS code
gulp.task('compileSass', function() {
return gulp.src('src/assets/css/**/*.scss')
.pipe(sass())
.on('error', handleError)
.pipe(minifyCss())
.pipe(gulp.dest('dist/assets/css'))
.pipe(browserSync.reload({
stream: true
}))
});
//minify JS
gulp.task('uglifyJS', function() {
gulp.src('src/assets/js/**/*.js')
.pipe(uglify())
.on('error', handleError)
.pipe(gulp.dest('dist/assets/js'))
.pipe(browserSync.reload({
stream: true
}))
});
//watch tasks
gulp.task('watch', ['browserSync'], function() {
var rootDir = gulp.watch('src/*.html', ['syncHtmlRootDir']);
rootDir.on('change', function(ev) {
if(ev.type === 'deleted') {
del(path.relative('./', ev.path).replace('src','dist'));
}
});
var appDir = gulp.watch('src/app/**/*', ['syncHtmlAppDir']);
appDir.on('change', function(ev) {
if(ev.type === 'deleted') {
del(path.relative('./', ev.path).replace('src/app/','dist/app/'));
}
});
var imgDir = gulp.watch('src/assets/img/**/*', ['syncImgDir']);
imgDir.on('change', function(ev) {
if(ev.type === 'deleted') {
del(path.relative('./', ev.path).replace('src/assets/img/','dist/assets/img/'));
}
});
var jsDir = gulp.watch('src/assets/js/**/*', ['uglifyJS']);
jsDir.on('change', function(ev) {
if(ev.type === 'deleted') {
del(path.relative('./', ev.path).replace('src/assets/js/','dist/assets/js/'));
}
});
var cssDir = gulp.watch('src/assets/css/**/*', ['compileSass']);
cssDir.on('change', function(ev) {
if(ev.type === 'deleted') {
del(path.relative('./', ev.path).replace('src/assets/css/','dist/assets/css/'));
}
});
});
So I'm 1) looking to combine my repetitive copy tasks into fewer tasks 2)have the delete file function work on all copy tasks and 3) optimize my watch task function to reduce repetition.
p.s., I've also noticed that if I add new files to the watch folders, it won't "recognize" them until I restart the watch command, so my method of syncing isn't exactly bulletproof. =/
Your thoughts are most appreciated.
Thanks!