BrowserSync does not automatically refresh the page with gulp-jade - javascript

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 :)

Related

Gulp: How to concatenate files after they have compiled?

My goal is to compile and minify a few CSS and JS files, and one HTML file into a new HTML file which should have this kind of structure:
<script>
... compiled JS files ...
</script>
<style>
... minified CSS files ...
</style>
<html file>
This is my file structure:
This is my gulpfile:
const gulp = require('gulp');
const plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var csslint = require('gulp-csslint');
var cssComb = require('gulp-csscomb');
var cleanCss = require('gulp-clean-css');
var jshint = require('gulp-jshint'); // removed
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyHtml = require('gulp-minify-html');
const babel = require('gulp-babel');
const inject = require('gulp-inject-string');
const gulpMerge = require('gulp-merge');
const del = require('del');
const runSequence = require('gulp-sequence');
gulp.task('clean', function () {
return del([
'dist/**/*',
]);
});
gulp.task('css', function () {
gulp.src(['src/**/*.css'])
.pipe(plumber())
.pipe(cssComb())
.pipe(csslint())
.pipe(csslint.formatter())
.pipe(concat('bundle.css'))
.pipe(gulp.dest('dist/'))
.pipe(rename({
suffix: '.min'
}))
.pipe(cleanCss())
.pipe(gulp.dest('dist/'))
});
gulp.task('js', function () {
gulp.src(['src/js/**/*.js'])
.pipe(concat('bundle.js'))
.pipe(babel({
presets: 'env'
}))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(gulp.dest('dist/'))
.pipe(rename({
suffix: '.min'
}))
.pipe(uglify())
.pipe(gulp.dest('dist/'))
});
gulp.task('html', function () {
gulp.src(['src/html/**/*.html'])
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(minifyHtml())
.pipe(gulp.dest('dist/'))
});
gulp.task('concatenateFiles', function() {
return gulpMerge(
gulp.src('dist/bundle.css')
.pipe(inject.wrap("\n<style>\n", "\n</style>\n")),
gulp.src('dist/bundle.js')
.pipe(inject.wrap("\n<script>\n", "\n</script>\n\n")),
gulp.src('src/html/player.html')
)
.pipe(concat('widget.html'))
.pipe(gulp.dest('dist/'));
});
gulp.task('concatenateFilesMinified', function() {
return gulpMerge(
gulp.src('dist/bundle.min.css')
.pipe(inject.wrap('<style>', '</style>')),
gulp.src('dist/bundle.min.js')
.pipe(inject.wrap('<script>', '</script>')),
gulp.src('dist/player.min.html')
)
.pipe(concat('widget.min.html'))
.pipe(gulp.dest('dist/'));
});
const js = 'src/**/*.js';
const css = 'src/**/*.css';
const html = 'src/**/*.html';
const all = [js, css, html];
gulp.task('default', ['clean', 'js', 'css', 'html'], function () {
gulp.watch(js, ['js']);
gulp.watch(css, ['css']);
gulp.watch(html, ['html']);
setTimeout(function() {
runSequence(['concatenateFiles', 'concatenateFilesMinified']);
}, 2000);
});
I know this is a bad approach, especially if you look at the setTimeout(), but I'm just so lost at this point (and this is my first gulpfile).
I've also tried this:
gulp.task('default', ['clean', 'js', 'css', 'html', 'concatenateFiles', 'concatenateFilesMinified'], function () {
gulp.watch(js, ['js']);
gulp.watch(css, ['css']);
gulp.watch(html, ['html']);
});
But the problem is that all dependency tasks are executed in parallel, so the 'concatenateFiles' and 'concatenateFilesMinified' are started before their dependencies (eg JS, CSS and HTML) are ready.
Furthermore, gulp.watch() would only work for js, css and html tasks.
How do I do this properly?
TLDR:
I want to:
build CSS, JS and HTML files from src folder (1 file for each type)
concatenate those three files into one file (wrapping JS into <script>, CSS into <style>) into dist/widget.html
minify the file from step 2. into dist/widget.min.html
I want these 3 things to happen when I run gulp default.
Furthermore, I also want files from step 2. and 3. to be refreshed every time I make changes to files in src/ folder
runSequence should work with tasks, which are returning something. Add 'return' for js, html, concatenateFiles, concatenateFilesMinified

BrowserSync Not Loading

Very new to BrowserSync. I'm trying to find out how to get it going haha.
My main file that stores everything is called 'gulpwork'.
Inside it I have 4 folders; two to convert Pug ('src') to HTML ('dist') and two to convert SASS ('sass') to CSS ('css').
I've managed to get BrowserSync to run however I'm getting the 'Cannot GET /' message so I know it probably has something to do with file directory.
I would like to have both Pug and SASS synced.
EDIT: It only works if I have both my Pug and HTML file outside their respected folders directly inside my root and it only works if the HTML file is named index.html. How can I get it to work in its respected folders and without having to change the name to index?
Here is my gulpfile.js code:
JS:
var gulp = require('gulp');
var pug = require('gulp-pug');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('browserSync', ['sass', 'pug'], function() {
browserSync.init({
server: {
baseDir: './'
}
})
});
gulp.task('pug', function() {
gulp.src('./src/*.pug')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('./dist'))
});
gulp.task('sass', function() {
return gulp.src('./sass/*.sass')
.pipe(sass())
.pipe(gulp.dest('./css'))
.pipe(browserSync.reload({stream: true}))
});
gulp.task('watch', ['browserSync'], function() {
gulp.watch('./src/*.pug', ['pug']);
gulp.watch('./sass/*.sass', ['sass']);
gulp.watch('./dist/*.html').on('change', browserSync.reload);
});
gulp.task('default', ['sass', 'pug', 'watch']);
Figured it out. BrowserSync looks for an 'index.html' file to start up and we get the 'cannot GET /' error because it's looking for something it doesn't see. So wherever our pug/html files are located, we must tell the pug function + the watch function where they are and then run BrowserSync. After it's run, you will still see the error however it's really working. All you have to do is link to the file so in my browser after localhost:3000 I would type the location of my file, so it would be 'localhost:3000/dist/about.html' After that, BrowserSync works. :)
var gulp = require('gulp');
var pug = require('gulp-pug');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('browserSync', ['sass', 'pug'], function() {
browserSync.init({
server: {
baseDir: './'
}
})
});
gulp.task('pug', function() {
gulp.src('./src/*.pug')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('sass', function() {
return gulp.src('./sass/*.sass')
.pipe(sass())
.pipe(gulp.dest('./css'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('watch', ['browserSync'], function() {
gulp.watch('./src/*.pug', ['pug']);
gulp.watch('./sass/*.sass', ['sass']);
gulp.watch('./dist/*.html').on('change', browserSync.reload);
});
gulp.task('default', ['sass', 'pug', 'watch']);
gulp.task('browser-sync', function() {
browserSync.init({
watch: true, // <-- Adding this line solved my reload problem
server: {
baseDir: './'
},
port: 8080 // <-- If you have problems with port 3000 try changing it like this
});
});

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']);

BrowserSync refreshing before injection (Gulp)

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.]

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.

Categories

Resources