So basically what I'm trying to do is to make the browser refresh whenever there is a change in the files using browserSync, compiles Pug templates, then Parceljs does the bundling. And Gulp is to watch for changes.
The overall objective is a static website/page.
The problem:
If parcel fails building. browserSync exits. Watch stops.
[12:31:41] 'parcel' errored after 3.83 s
[12:31:41] Error in plugin "gulp-parcel"
[12:31:41] The following tasks did not complete: browserSync
[12:31:41] Did you forget to signal async completion?
OS: Windows 10
Thanks!!
Gulpfile.js content:
"use strict";
var gulp = require('gulp');
var parcel = require('gulp-parcel');
var pug = require('gulp-pug');
var browserSync = require('browser-sync').create();
gulp.task('html', function () {
return gulp.src('src/templates/*.pug')
.pipe(pug())
.pipe(gulp.dest('build/html'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('parcel', function () {
return gulp.src('build/html/*.html', {
read: false
})
.pipe(parcel())
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'dist'
},
});
});
gulp.task('watch', gulp.parallel('browserSync',gulp.series('html', 'parcel')), function () {
gulp.watch('src/templates/**/*.pug', gulp.series('html', 'parcel'));
});
gulp.task('default', gulp.series('watch'), function(){
console.log('Started default');
});
After investigating a bit, the gulp-parcel plugin had a bug which is still being worked on. Meanwhile, I was able to come up with a workaround.
Upgraded to es6
Implemented 'gulp-run-command' to run Parcel in watch mode
Here is my new solution:
'use strict';
import gulp from 'gulp';
import babel from 'gulp-babel';
import browserSync from 'browser-sync';
import run from 'gulp-run-command';
import log from 'fancy-log';
import errorHandler from 'gulp-error-handle';
const server = browserSync.create();
const paths = {
parcel: {
dist: 'dist/*'
}
};
gulp.task('parcel', run('parcel watch src/templates/index.pug --public-url ./ --no-cache'));
const reload = done => {
server.reload();
done();
};
const serve = done => {
server.init({
server: {
baseDir: 'dist/'
}
});
done();
};
const watch = done => {
gulp.watch(paths.parcel.dist, gulp.series(reload));
done();
};
const dev = gulp.parallel('parcel', serve, watch);
export default dev;
Related
I keep getting an error "Identifier 'browserSync' has already been declared" but i cant see where the problem is.Here is my code
// Watch files
function watchFiles() {
gulp.watch("*.js", gulp.series(scriptsLint, scripts, browserSyncReload));
gulp.watch(["processHTML"], gulp.series(browserSyncReload));
}
//Task Live Reload
function browserSync(done) {
browserSync.init({
server: './dist',
port: 8080,
ui: {
port: 8081
}
})
done()
};
// BrowserSync Reload
function browserSyncReload(done) {
browserSync.reload();
done();
}
// define complex tasks
const js = gulp.series(scriptsLint, scripts);
const build = gulp.parallel(processHTML,js);
const watch = gulp.parallel(watchFiles, browserSync);
You need to rename your function browserSync to other name, because that's a keyword reserved for the BrowserSync library.
Something like this:
// Watch files
function watchFiles() {
gulp.watch("*.js", gulp.series(scriptsLint, scripts, reload));
gulp.watch(["processHTML"], gulp.series(reload));
}
//Task Live Reload
function localServer(done) {
browserSync.init({
server: './dist',
port: 8080,
ui: {
port: 8081
}
})
done()
};
// BrowserSync Reload
function reload(done) {
browserSync.reload();
done();
}
// define complex tasks
const js = gulp.series(scriptsLint, scripts);
const build = gulp.parallel(processHTML,js);
const watch = gulp.parallel(watchFiles, localServer);
Your browserSync() function, declared in line 9, is named the same as another variable in its scope, browserSync (in line 10), and needs to be renamed.
// Watch files
function watchFiles() {
gulp.watch("*.js", gulp.series(scriptsLint, scripts, browserSyncReload));
gulp.watch(["processHTML"], gulp.series(browserSyncReload));
}
//Task Live Reload
function browserSyncFunc(done) {
browserSync.init({
server: './dist',
port: 8080,
ui: {
port: 8081
}
})
done()
};
// BrowserSync Reload
function browserSyncReload(done) {
browserSync.reload();
done();
}
// define complex tasks
const js = gulp.series(scriptsLint, scripts);
const build = gulp.parallel(processHTML,js);
const watch = gulp.parallel(watchFiles, browserSyncFunc /* I'm guessing you meant to use the browserSync function here, not the object */);
I am using Gulp to compile and minify my SASS. This works fine, but I want to extend the automation by using BrowserSync.
I've followed the instructions on a few tutorial sites but cannot get it working - the browser does not refresh when I update either my .scss or .html files, not do any errors appear on the Terminal.
My gulpfile.js is as such. Would anyone know why browserSync fails to run?
(ps running gulp browserSync does sucessfully open the browser window and index file with http://localhost:3000/ but there is no automatic refreshing).
const gulp = require('gulp');
const sass = require('gulp-sass');
const cssnano = require('gulp-cssnano');
const browserSync = require('browser-sync').create();
// Normal .scss compilation
gulp.task('sass', function(){
return gulp.src('scss/main.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'))
});
// Minifys .css, is meant to reload browser
gulp.task('mini-css', function() {
return gulp.src('dist/css/main.css')
.pipe(cssnano())
.pipe(gulp.dest('dist/css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Do both of the above
gulp.task('do-sass', gulp.series('sass', 'mini-css'))
gulp.task('watch', function(){
gulp.watch('scss/**/*.scss', gulp.series('do-sass'));
gulp.watch("*.html").on('change', browserSync.reload);
});
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: './'
},
})
})
Your watch task should be your default task. Try to put the browserSync.init() in the watch task und then start your gulp with gulp watch
const gulp = require('gulp');
const sass = require('gulp-sass');
const cssnano = require('gulp-cssnano');
const browserSync = require('browser-sync').create();
// Normal .scss compilation
gulp.task('sass', function(){
return gulp.src('scss/main.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'))
});
// Minifys .css, is meant to reload browser
gulp.task('mini-css', function() {
return gulp.src('dist/css/main.css')
.pipe(cssnano())
.pipe(gulp.dest('dist/css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Do both of the above
gulp.task('do-sass', gulp.series('sass', 'mini-css'))
gulp.task('watch', function(){
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('scss/**/*.scss', gulp.series('do-sass'));
gulp.watch("*.html").on('change', browserSync.reload);
});
Gulp setup is working fine for me in local.
But i want like if i change files in local then it will build and uploaded to live server automatically (minified css and js/compiled css/js).
I have tried gulp-rsync, vinyl-ftp but couldn't succeed may be i don't know how to use above packages.
Here is a my gulp file.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
// Development Tasks
// -----------------
// Start browserSync server
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app'
}
})
})
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss and children dirs
.pipe(sass().on('error', sass.logError)) // Passes it through a gulp-sass, log errors to console
.pipe(gulp.dest('app/css')) // Outputs it in the css folder
.pipe(browserSync.reload({ // Reloading with Browser Sync
stream: true
}));
})
// Watchers
gulp.task('watch', function() {
gulp.watch('app/scss/**/*.scss', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
})
// Optimization Tasks
// ------------------
// Optimizing CSS and JavaScript
gulp.task('useref', function() {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
// Optimizing Images
gulp.task('images', function() {
return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true,
})))
.pipe(gulp.dest('dist/images'))
});
// Copying fonts
gulp.task('fonts', function() {
return gulp.src('app/fonts/**/*')
.pipe(gulp.dest('dist/fonts'))
})
// Cleaning
gulp.task('clean', function() {
return del.sync('dist').then(function(cb) {
return cache.clearAll(cb);
});
})
gulp.task('clean:dist', function() {
return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});
// Build Sequences
// ---------------
gulp.task('default', function(callback) {
runSequence(['sass', 'browserSync'], 'watch',
callback
)
})
gulp.task('build', function(callback) {
runSequence(
'clean:dist',
'sass',
['useref', 'images', 'fonts'],
callback
)
})
And here is a my folder structure.
This is main folder
It's a development folder
And this one is production folder in which all files are build.
My Gulp was working fine until I installed browser-sync
npm install browser-sync gulp --save-dev
Then I started to get this error:
Error: Cannot find module 'lru-cache'
Which I solved using this: npm link lru-cache answer from https://github.com/npm/npm/issues/1154
However, now when I try to run gulp I get this new error:
~/Projects/starfeeder
❯ npm install browser-sync gulp --save-dev
npm WARN deprecated minimatch#2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated node-uuid#1.4.8: Use uuid module instead
fsevents#1.1.2 install
/Users/leongaban/Projects/starfeeder/node_modules/fsevents
node install
My gulpfile if that helps:
"use strict";
const gulp = require('gulp'),
_ = require('lodash'), // https://www.npmjs.com/package/lodash
del = require('del'), // https://www.npmjs.com/package/del
fs = require('fs'), // Node file system
gutil = require('gulp-util'), // https://www.npmjs.com/package/gulp-util
htmlReplace = require('gulp-html-replace'), // https://www.npmjs.com/package/gulp-html-replace
notify = require("gulp-notify"), // https://www.npmjs.com/package/gulp-notify
runSequence = require('run-sequence'), // https://www.npmjs.com/package/run-sequence
sass = require('gulp-ruby-sass'), // https://www.npmjs.com/package/gulp-ruby-sass
sourcemaps = require('gulp-sourcemaps'); // https://www.npmjs.com/package/gulp-sourcemaps
const rootPath = process.cwd();
const paths = {
files: ['src/static/**']
};
const errorlog = err => {
gutil.log(gutil.colors.red.bold.inverse(' ERROR: '+err));
this.emit('end');
};
// Build tasks chain ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
gulp.task('build', function(cb) {
runSequence(
'build:app-css', // Minify and concat app styles
'build:move-files',
'build:index', // Replace scripts in index.html
'build:final', cb); // Remove app.min.js from build folder
});
gulp.task('build:move-files', () => gulp.src(paths.files).pipe(gulp.dest('starfeeder/')) );
// Preprocess SASS into CSS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:app-css', () => sass('src/sass/starfeeder.scss', { style: 'compressed' }).on('error', errorlog).pipe(gulp.dest('src/static/css/')) );
// Clear out all files and folders from build folder \\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:cleanfolder', cb => { del(['starfeeder/**'], cb); });
// Task to make the index file production ready \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:index', () => {
process.stdout.write(gutil.colors.white.inverse(' New asset paths in markup: \n'));
process.stdout.write(gutil.colors.yellow(' static/css/starfeeder.css\n'));
gulp.src('index.html')
.pipe(htmlReplace({
'app-css': 'css/starfeeder.css'
}))
.pipe(gulp.dest('starfeeder/'))
.pipe(notify('Starfeeder build created!'));
});
gulp.task('build:final', cb => {
process.stdout.write(gutil.colors.blue.bold ('###################################################### \n'));
process.stdout.write(gutil.colors.blue.inverse(' Starfeeder build created! \n'));
process.stdout.write(gutil.colors.blue.bold ('###################################################### \n'));
});
// Main Styles /////////////////////////////////////////////////////////////////
gulp.task('app-css', () => {
return sass('src/sass/starfeeder.scss', { style: 'compressed' })
.pipe(sourcemaps.init())
.on('error', errorlog)
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('src/static/css/'))
});
// Development watch /////////////////////////////////////////////////////////// 🤖☕️⏎→
gulp.task('watch', () => {
gulp.watch('src/sass/**/*.scss', ['app-css']).on('change', file => {
let filePath = file.path.split(rootPath);
logFileChanged(filePath[1]);
});
});
gulp.task('default', ['watch']);
I had this same issue with installing through2. The project used shrink wrap and had a package-lock.json which caused the a dependencies to break. Once I removed the lock and re-installed, all was good.
Ok so still not sure why I got those errors, but never installing browserSync again.
I had to npm link all my gulp plugins.
That work, but then it broke during the gulp build process.
Instead of doing npm link to everything, included other node modules I've never heard off. I removed browserSync and deleted my node_modules folder and did yarn(npm) install.
I'm receiving an Unhandled rejection Error: ENOENT: no such file or directory, stat 'path/to/file'when I'm running a gulp task, even though the file in question does exist at that exact path.
Here is the gulp log:
15:35:46] Requiring external module babel-register
[15:35:57] Using gulpfile ~/Path/To/Project/gulpfile.babel.js
[15:35:57] Starting 'clean'...
[15:35:57] Finished 'clean' after 5.08 ms
[15:35:57] Starting 'dev'...
[15:35:57] Starting 'ghost'...
[15:35:57] Finished 'ghost' after 7.44 ms
[15:35:57] Starting 'styles'...
[15:35:57] Starting 'pug'...
[15:35:57] Starting 'browserify'...
[15:35:57] Rebundle...
Unhandled rejection Error: ENOENT: no such file or directory path/to/node_modules/ghost/content/themes/submittedly'
The file actually does exists, as you can see here:
file exists
My development workflow includes firing up a ghost server which works without the use of compilers, such as browserify, but in my case, I need a compiler for the code.
I'm assuming the error either occurs in the "browserify" task or the "browserSync" task: Here is the code for both:
Browserify:
'use strict';
import gulp from 'gulp';
import gulpif from 'gulp-if';
import gutil from 'gulp-util';
import source from 'vinyl-source-stream';
import streamify from 'gulp-streamify';
import sourcemaps from 'gulp-sourcemaps';
import rename from 'gulp-rename';
import watchify from 'watchify';
import browserify from 'browserify';
import babelify from 'babelify';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
import debowerify from 'debowerify';
import handleErrors from '../util/handle-errors';
import config from '../config';
// Based on: http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
function buildScript(file, watch) {
let bundler = browserify({
entries: ['./src/assets/js/' + file],
debug: !global.isProd,
cache: {},
packageCache: {},
fullPaths: global.isProd ? false : true
});
if ( watch ) {
bundler = watchify(bundler);
bundler.on('update', rebundle);
}
bundler.transform(babelify);
bundler.transform(debowerify);
function rebundle() {
const stream = bundler.bundle();
gutil.log('Rebundle...');
return stream.on('error', handleErrors)
.pipe(source(file))
.pipe(gulpif(global.isProd, streamify(uglify())))
.pipe(streamify(rename({
basename: 'main'
})))
.pipe(gulpif(!global.isProd, sourcemaps.write('./')))
.pipe(gulp.dest(config.dest.js))
.pipe(gulpif(browserSync.active, browserSync.reload({ stream: true, once: true })));
}
BrowserSync:
'use strict';
import url from 'url';
import browserSync from 'browser-sync';
import gulp from 'gulp';
import config from '../config';
gulp.task('browserSync', () => {
const DEFAULT_FILE = 'index.hbs';
const ASSET_EXTENSION_REGEX = new RegExp(`\\b(?!\\?)\\.(${config.assetExtensions.join('|')})\\b(?!\\.)`, 'i');
/*browserSync.use('logger', function () {
return function (emitter) {
emitter.on('init', function (data) {
console.log('Server started... go to http://localhost:2368');
});
}
});*/
browserSync.init({
server: {
baseDir: config.dest.dir,
middleware: function(req, res, next) {
const fileHref = url.parse(req.url).href;
if ( !ASSET_EXTENSION_REGEX.test(fileHref)) {
req.url = '/' + DEFAULT_FILE;
}
return next();
}
},
open: false,
port: config.browserPort,
ui: {
port: config.UIPort
},
ghostMode: {
links: false
}
});
});
These are the tasks I run for my workflow:
'use strict';
import gulp from 'gulp';
import runSequence from 'run-sequence';
gulp.task('dev', ['clean'], function(cb) {
cb = cb || function() {};
global.isProd = false;
return runSequence(['ghost', 'styles', 'pug', 'browserify'], 'watch', cb);
});
and this is my workflow setup:
workflow