BrowserSync refreshing before injection (Gulp) - javascript

I have my gulpfile:
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var sourcemaps = require('gulp-sourcemaps');
var fileinclude = require('gulp-file-include');
var browserify = require('browserify');
var rename = require('gulp-rename');
var streamify = require('gulp-streamify'); // required for uglify
var uglify = require('gulp-uglify'); // minify JS
var source = require('vinyl-source-stream'); // required to dest() for browserify
var browserSync = require('browser-sync').create();
var localSettings = require('./gulp/localConfig.js');
gulp.task('sass', function () {
return gulp.src('./assets/sass/main.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError)) // .on('error', sass.logError) prevents gulp from crashing when saving a typo or syntax error
.pipe(sourcemaps.write())
.pipe(gulp.dest('./assets/sass'))
.pipe(browserSync.stream()); // causes injection of styles on save
});
gulp.task('compileHTML', function() {
return gulp.src(['static/src/*.html'])
.pipe(fileinclude({
prefix: '##',
basepath: '#root'
}))
.pipe(gulp.dest('./static/compiled'))
.pipe(browserSync.stream()); // causes injection of html changes on save
});
// Static Server for browsersync
gulp.task('sync', ['sass'], function() {
browserSync.init({
startPath: "static/compiled/index.html",
open: localSettings.openBrowserSyncServerOnBuild,
server: {
baseDir: "./",
}
});
});
gulp.task('watch', function() {
gulp.watch('./assets/sass/**/*.scss', ['sass']);
gulp.watch(['./static/src/**/*.html', '!partials', '!components'], ['compileHTML']);
gulp.watch('./assets/js/**/*.js', ['javascript']);
});
gulp.task('javascript', function() {
var bundleStream = browserify('./assets/js/main.js').bundle();
bundleStream
.pipe(source('main.js'))
.pipe(rename('bundle.js'))
.pipe(gulp.dest('./assets/js/'))
.pipe(browserSync.stream());
})
// Default Task
gulp.task('default', ['compileHTML', 'javascript', 'sass', 'watch', 'sync']);
Mostly everything with my build works great, however I am having one issue with my compileHTML task. When any modifications are made to my html, it is compiled and injected into the page with BrowserSync. The problem is that BrowserSync is injecting the markup into the page AFTER it reloads, so that I have to manually refresh or save the file again.
Although I am doing the exact same thing with my SASS task, I have no problems with that task. Why do my styles inject into the page before the reload, but the HTML does not?
Just for testing, I tried adding a setTimout surrounding the BrowserSync injection, but it did not affect the timing of the injection other than adding a delay.

I would try to follow the example at gulp-reload docs. Their example is:
// create a task that ensures the `js` task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
browserSync.reload();
done();
});
So you try :
gulp.watch(['./static/src/**/*.html', '!partials', '!components'], ['compileHTML'],
function (done) {
browserSync.reload();
done();
});
And remove the pipe browserSync.stream() in your 'complieHTML' task.
[I might first try as a very simple attempt changing from stream() to reload() in that task before the changes above.]

Related

Jquery library not working after gulp bundle

I am quite a newbie for gulp but i am trying to implement it in my this project. But looks like somewhere i mashup. I order the js files and was trying to get the bundle. But looks like jquery lib or something is not working.
Here is my gulpfile.js code:
'use strict';
// include all necessary plugins in gulp file
var gulp = require('gulp');
var order = require('gulp-order');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
// Task defined for java scripts bundling and minifying
gulp.task('scripts', function() {
return gulp.src('assets/src/js/*.js')
.pipe(order([
"assets/src/js/jquery-3.2.1.slim.min.js",
"assets/src/popper.min.js",
"assets/src/js/bootstrap.min.js",
"assets/src/js/morphext.min.js",
"assets/src/js/pushy.min.js",
"assets/src/quote.js"
], { base: './' }))
.pipe(concat('bundle.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('assets/dist/js'));
});
// Task define for compliling scss file
// Currently i am not using this complier
gulp.task('sass', function() {
return gulp.src('assets/src/css/**/*.scss', {style: 'compressed'})
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.init()) // Process the original sources
.pipe(sass())
.pipe(sourcemaps.write()) // Add the map to modified source.
.pipe(gulp.dest('assets/dist/css/'));
});
// Define task to optimize images in project
gulp.task('images', function() {
return gulp.src('assets/src/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/dist//img'));
});
// Task watch
gulp.task('watch', function() {
// Watch .js files
gulp.watch('assets/src/js/*.js', ['scripts']);
// Watch .scss files
gulp.watch('assets/src/css/*.scss', ['sass']);
// Watch image files
gulp.watch('assets/src/img/**/*', ['images']);
});
// declaring final task and command tasker
// just hit the command "gulp" it will run the following tasks...
gulp.task('default', ['scripts', 'images' , 'watch']);
I got solution for this problem, here is my new code for gulp.js!
'use strict';
// include all necessary plugins in gulp file
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
// Task defined for java scripts bundling and minifying
gulp.task('scripts', function() {
return gulp.src
([
'assets/src/js/jquery/*.js',
'assets/src/js/vendor/*.js',
'assets/src/js/plugins/*.js',
'assets/src/js/custom/*.js',
])
.pipe(concat('bundle.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('assets/dist/js/'));
});
// Task define for compliling scss file
gulp.task('sass', function() {
return gulp.src('assets/src/scss/**/*.scss', {style: 'compressed'})
.pipe(rename({suffix: 'custom'}))
.pipe(sourcemaps.init()) // Process the original sources
.pipe(sass())
.pipe(sourcemaps.write()) // Add the map to modified source.
.pipe(gulp.dest('assets/dist/css/unminified/'));
});
// Define task to optimize images in project
gulp.task('images', function() {
return gulp.src('assets/src/img/**/*')
.pipe(cache(imagemin({ optimizationLevel:5, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/dist/img'));
});
// Task watch
gulp.task('watch', function() {
// Watch .js files
gulp.watch('assets/src/js/*.js', ['scripts']);
// Watch .scss files
gulp.watch('assets/src/scss/*.scss', ['sass']);
// Watch image files
gulp.watch('assets/src/img/**/*', ['images']);
});
// declaring final task and command tasker
// just hit the command "gulp" it will run the following tasks...
gulp.task('default', ['scripts', 'images' , 'sass' , 'watch']);

BrowserSync does not automatically refresh the page with gulp-jade

I recently created a workspace with gulp. Everything was working normally (auto-reload, sass compilation, minification, and more)
You can see the code on github
Today I wanted to add jade to the project. The compilation works well but browserSync does not refresh the page automatically
Here is my code
'use strict'
var gulp = require('gulp')
var jade = require('gulp-jade')
var sass = require('gulp-sass')
var cssmin = require('gulp-cssmin')
var rename = require('gulp-rename')
var prefix = require('gulp-autoprefixer')
var uglify = require('gulp-uglify')
var concat = require('gulp-concat')
var imagemin = require('gulp-imagemin')
var browserSync = require('browser-sync').create()
// Compile Jade
gulp.task('jade', function () {
gulp.src('src/*.jade')
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('./dist'))
})
// Configure CSS tasks.
gulp.task('sass', function () {
gulp.src('src/scss/**/*.scss')
.pipe(sass.sync().on('error', sass.logError))
.pipe(prefix('last 2 versions'))
.pipe(cssmin())
.pipe(concat('styles.css'))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/css'))
.pipe(browserSync.stream())
})
// Configure JS.
gulp.task('js', function () {
gulp.src('src/js/**/*.js')
.pipe(uglify())
.pipe(concat('app.js'))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/js'))
.pipe(browserSync.stream())
})
// Configure image stuff.
gulp.task('images', function () {
gulp.src('src/img/**/*.+(png|jpg|gif|svg)')
.pipe(imagemin())
.pipe(gulp.dest('dist/img'))
.pipe(browserSync.stream())
})
gulp.task('default', ['jade', 'sass', 'js', 'images'], function () {
browserSync.init({
server: './dist'
})
gulp.watch('src/*.jade', ['jade'])
gulp.watch('src/scss/**/*.scss', ['sass'])
gulp.watch('src/js/**/*.js', ['js'])
gulp.watch('./dist/*.html').on('change', browserSync.reload)
})
I tested the code and found the error.
Browsersync gets injected into <head> element, therefore you need to have that element on your page (still its good to have html/head/body).
Implementing my suggestion from comment (about missing browserSync.stream()) and fixing your jade file to:
html
head
body
h1 hello Jade
ul
li comment ça va
li et toi ?
.box salut comment tu vas ?
Solves the problem. BrowserSync now correctly gets inserted into the page :)

Local changes to file in node_modules (Angular 2)

I know that this can be a very stupid question, but I can't find matches with other posts on stackoverflow...
So: Can I modify a file of an external module , just save the file and do something that my app can listen?
At the moment, i'm trying ti change some scss style at the ng2-datepicker module (inside node_modules folder), but if I save and the launch ng serve, changes will not affect my project.
I know it's a simple problem, but i don't know the background architecture of an Angular2 project.
Thanks in advance.
(ps I've seen that i can fork the git and then do something like npm install.
Very interesting, but i also want to know how to have the same result in local)
If you are using gulp file you can tell the changed lib file path to copy to build folder check gulp.task('copy-libs') in code below git repo for angular2-tour-of-heroes using gulp
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync');
const reload = browserSync.reload;
const tsconfig = require('tsconfig-glob');
// clean the contents of the distribution directory
gulp.task('clean', function () {
return del('dist/**/*');
});
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', ['clean'], function() {
return gulp.src(['app/**/*', 'index.html', 'styles.css', '!app/**/*.ts'], { base : './' })
.pipe(gulp.dest('dist'))
});
// copy dependencies
gulp.task('copy:libs', ['clean'], function() {
return gulp.src([
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js',
'node_modules/node-uuid/uuid.js',
'node_modules/immutable/dist/immutable.js'
'yourpath/changedFileName.js'
])
.pipe(gulp.dest('dist/lib'))
});
// linting
gulp.task('tslint', function() {
return gulp.src('app/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// TypeScript compile
gulp.task('compile', ['clean'], function () {
return gulp
.src(tscConfig.files)
.pipe(sourcemaps.init())
.pipe(typescript(tscConfig.compilerOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/app'));
});
// update the tsconfig files based on the glob pattern
gulp.task('tsconfig-glob', function () {
return tsconfig({
configPath: '.',
indent: 2
});
});
// Run browsersync for development
gulp.task('serve', ['build'], function() {
browserSync({
server: {
baseDir: 'dist'
}
});
gulp.watch(['app/**/*', 'index.html', 'styles.css'], ['buildAndReload']);
});
gulp.task('build', ['tslint', 'compile', 'copy:libs', 'copy:assets']);
gulp.task('buildAndReload', ['build'], reload);
gulp.task('default', ['build']);

Update: Errors with postCSS and Babel in Gulpfile

Goal
I'm updating my old gulpfile.js, which used to be mainly for compiling my Sass into CSS, but now I'm trying to get Gulp to do the following:
Sync browser, whip up localhost server - DONE
Compile Sass => CSS - DONE
Show any JavaScript errors with JSHint - DONE
Compile ES6 => ES6 with Babel (WORKING ON)
Minify all assets (WORKING ON)
Show project file size - DONE
Deploy index.html, style.css and images to S3 (WORKING ON)
Watch files, reload browser when .scss or .html changes - DONE
Problem
Trying to minify my Javascript and also create a scripts.min.js
file, it keeps adding the suffix min to every new minified JavaScript
file.
Folder structure
index.html
gulpfile.js
package.json
.aws.json
.csscomb.json
.gitignore
assets
- css
style.css
style.scss
--partials
---base
---components
---modules
- img
- js
scripts.js
- dist
gulpfile.js
// Include Gulp
var gulp = require('gulp');
var postcss = require("gulp-postcss");
// All of your plugins
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync');
var cache = require('gulp-cache');
var concat = require('gulp-concat');
var csswring = require("csswring");
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lost = require("lost");
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var rucksack = require("rucksack-css");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
// Sync browser, whip up server
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Reload page automagically
gulp.task('bs-reload', function () {
browserSync.reload();
});
// Compile Sass into CSS, apply postprocessors
gulp.task('styles', function(){
var processors = [
autoprefixer({browsers: ['last 2 version']}),
csswring,
lost,
rucksack
];
gulp.src(['assets/css/**/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sass())
.pipe(postcss(processors))
// .pipe(gulp.dest('assets/css/'))
// .pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('assets/css/'))
.pipe(browserSync.reload({stream:true}))
});
// Show any JavaScript errors
gulp.task('scripts', function(){
return gulp.src('assets/js/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(jshint())
.pipe(jshint.reporter('default'))
// .pipe(concat('main.js'))
// .pipe(babel())
.pipe(gulp.dest('assets/js/'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'))
.pipe(rename({suffix: '.min'}))
.pipe(browserSync.reload({stream:true}))
});
// Minify assets, create build folder
gulp.task('images', function(){
gulp.src('assets/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/img'));
});
// Minify HTML
// Default task
gulp.task('default', ['browser-sync'], function(){
gulp.watch("assets/css/**/*.scss", ['styles']);
gulp.watch("assets/js/**/*.js", ['scripts']);
gulp.watch("*.html", ['bs-reload']);
gulp.start("images", "styles", "scripts")
});
// var babel = require('gulp-babel');
// var minifyhtml = require("gulp-minify-html");
// var size = require("gulp-size");
// var upload = require("gulp-s3");
Hi i can't solve all your problems but I had also a similar issue with the babel and ES6 fat arrow functions (using babelify and browserify). To solve the problem try to pass:
stage: 0
to your babel.js gulp plugin. If error will still occurs then try to pass also:
experimental: true
For more information please have a look "experimental" section on babel.js site.

gulp.watch() not running subsequent task

Running into a bizarre bug when trying to make modular gulp tasks by splitting them into separate files. The following should execute the task css, but does not:
File: watch.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', ['css']); // PROBLEM
});
Declaring ['css'] in plugins.watch() should technically run the following task next:
File: css.js
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('css', function () {
return gulp.src('assets/styl/*.styl')
.pipe(plugins.stylus())
.pipe(gulp.dest('/assets/css'));
});
File: gulpfile.js
var gulp = require('gulp');
var requireDir = require('require-dir');
requireDir('./gulp/tasks', { recurse: true });
gulp.task('develop', ['css', 'watch']);
Folder structure
- gulp/
- tasks/
- css.js
- watch.js
- gulpfile.js
Expected behavior
gulp develop should run tasks css and watch (it does). On file changes, watch should detect them (it does) and then run the css task (it's does not).
One solution
Not terribly fond of this solution as gulp.start() is being deprecated in the next release, but this does fix it:
File: watch.js
plugins.watch('assets/styl/**/*.styl', function() {
gulp.start('css');
});
Either use gulp's builtin watch with this syntax:
gulp.task('watch', function () {
gulp.watch('assets/styl/**/*.styl', ['css']);
});
Or gulp-watch plugin with this syntax:
gulp.task('watch', function () {
plugins.watch('assets/styl/**/*.styl', function (files, cb) {
gulp.start('css', cb);
});
});
There's also probably a typo in your gulp.dest path. Change it to relative:
.pipe(gulp.dest('assets/css'));
I am using Gulp 4, where gulp.start() is deprecated
So here's the solution
gulp.task('watch', gulp.series('some-task-name', function () {
browserSync.init({
server: {
baseDir: config.distFolder + ''
}
});
var watcher = gulp.watch([
'./src/views/*.html',
'./src/index.html',
'./src/assets/css/*.css',
'./src/**/*.js'],
gulp.series('some-task-name'));
watcher.on('change', async function (path, stats) {
console.log('you changed the code');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
}));
Now, whenever there is a change in my code, my "some-task-name" gets executed and then the browser page is reloaded. I don't need to delay my browser-sync at all.

Categories

Resources