I have a Gulp + Browsersync setup which is compiling everything but when I try to view the site in the browser the localhost (Access URLs) is not working.
my code looks like below:
const browsersync = done => {
browserSync.init({
proxy: config.projectURL, // Proxing website.local:8000
open: config.browserAutoOpen, //false
injectChanges: config.injectChanges, //true
watchEvents: [ 'change', 'add', 'unlink', 'addDir', 'unlinkDir' ]
});
done();
};
// Helper function to allow browser reload with Gulp 4.
const reload = done => {
browserSync.reload();
done();
};
Running as follows:
gulp.task(
'default',
gulp.parallel( 'styles', 'customJS', 'images', browsersync, () => {
gulp.watch( config.watchPhp, reload ); // Reload on PHP file changes.
gulp.watch( config.watchStyles, gulp.parallel( 'styles' ) ); // Reload on SCSS file changes.
gulp.watch( config.watchJsCustom, gulp.series( 'customJS', reload ) ); // Reload on customJS file changes.
gulp.watch( config.imgSRC, gulp.series( 'images', reload ) ); // Reload on customJS file changes.
})
);
Any ideas would be greatly appreciated.
Thanks
Related
I'm trying to watch 2 sets of folders. One set just requires a browser reload on change. The second requires "reinitializing the framework", via a separate, background http get before doing the reload.
My current attempt handles this properly once, but only once. Can you tell me both why and how to fix it? The troublesome portion is in the second watch task.
const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create();
const { reload } = bs;
const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";
var paths = {
refresh: [
"./layouts/**/*.*",
"./views/**/*.*",
"./includes/**/*.js",
"./includes/**/*.css"
],
reinit: [
"./handlers/**/*.*",
"./models/**/*.*",
"./interceptors/**/*.*",
"./config/**/*.*"
]
}
gulp.task('watch', () => {
gulp.watch(paths.refresh, (done) => {
reload();
done();
});
gulp.watch(paths.reinit, () => {
console.log("Reinitializing framework");
axios.get(url)
.then(response => {
console.log(response.data.trim());
reload();
})
.catch(error => {
console.log("Error: Please ensure you have a /healthcheck route set up in /config/router.cfc!");
console.log("Error: Once you've done that, please shut down commandbox then try browsersync again.");
});
});
});
gulp.task('proxy', () => {
bs.init({
proxy: "localhost:80",
port: 81,
open: true,
notify: false
});
});
gulp.task('default', gulp.parallel('watch', 'proxy'));
Gulp watch passes a "done" callback that must be called in order to proceed. Changing the code to the following solved the problem.
const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create();
const { reload } = bs;
const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";
var paths = {
refresh: [
"./layouts/**/*.*",
"./views/**/*.*",
"./includes/**/*.js",
"./includes/**/*.css"
],
reinit: [
"./handlers/**/*.*",
"./models/**/*.*",
"./interceptors/**/*.*",
"./config/**/*.*"
]
}
gulp.task('watch', () => {
gulp.watch(paths.refresh, (done) => {
reload();
done();
});
gulp.watch(paths.reinit, (done) => {
console.log("Reinitializing framework");
axios.get(url)
.then(response => {
console.log(response.data.trim());
reload();
done();
})
.catch(error => {
console.log("Error: Please ensure you have a /healthcheck route set up in /config/router.cfc!");
console.log("Error: Once you've done that, please shut down commandbox then try browsersync again.");
});
});
});
gulp.task('proxy', () => {
bs.init({
proxy: "localhost:80",
port: 81,
open: true,
notify: false
});
});
gulp.task('default', gulp.parallel('watch', 'proxy'));
Being new to gulp. I have the follwing task. I need to spawn a webserver and then another script has to run some stuff against this webserver. I am currently struggling with finishing the script because the browser-sync task does not finish and prevents the script from exit.
'use strict';
const browserSync = require('browser-sync').create();
const cp = require('child_process');
const minimalcss = require('minimalcss');
const gulp = require('gulp');
const clean = require('gulp-clean');
const sourceDir = "_site/";
const deployDir = "public/";
// build the mkdocs Site
gulp.task('build', function() {
return cp.exec('pipenv run mkdocs build --site-dir ' + sourceDir);
});
// Delete _deploy directory first
gulp.task('prepare', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// Delete _deploy directory again // just for testing
gulp.task('cleanup', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// does not lead to anything, just for testing
gulp.task('inlinecriticalCSS', function(done) {
minimalcss
.minimize({ urls: ['http://localhost:9999/' + 'index.html'] })
.then(result => {
console.log('OUTPUT', result.finalCss.length, result.finalCss);
})
.catch(error => {
console.error(`Failed the minimize CSS: ${error}`);
});
done();
});
// webserver
gulp.task('serve', (done) => {
browserSync.init({
port: 9999,
server: {
baseDir: sourceDir
}
});
done();
});
// default sequence
gulp.task('default', gulp.series(
'prepare',
'build',
'serve',
'inlinecriticalCSS',
'cleanup')
);
I am learning the front-end build system currently gulp, i want to use brower-sync and the problem is it is not throwing an error in the commad line but instead when it brings up the browser it will not display my html file and it will say "Cannot GET /" error in the browser window. This is my gulpfile.js code
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
compass= require('gulp-compass'),
plumber = require('gulp-plumber'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync'),
reload = browserSync.reload,
rename = require('gulp-rename');
gulp.task('scripts', function() {
gulp.src(['public/src/js/**/*.js', '!public/src/js/**/*.min.js'])
.pipe(plumber())
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('public/src/js/'));
});
gulp.task('styles', function() {
gulp.src('public/src/scss/main.scss')
.pipe(plumber())
.pipe(compass({
config_file: './config.rb',
css: './public/src/css/',
sass: './public/src/scss/'
}))
.pipe(autoprefixer('last 2 versions'))
.pipe(gulp.dest('public/src/css/'))
.pipe(reload({stream:true}));
});
gulp.task('html', function() {
gulp.src('public/**/*.html');
});
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./public/"
}
});
});
gulp.task('watch', function() {
gulp.watch('public/src/js/**/*.js', ['scripts']);
gulp.watch('public/src/scss/**/*.scss', ['styles']);
gulp.watch('public/**/*.html', ['html']);
});
gulp.task('default', ['scripts', 'styles', 'html', 'browser-sync', 'watch']);
i am using windows and git bash and version is "browser-sync": "^2.12.5" so what is the problem and try to explain for me in order to get something out of it.
Is there an index.html file in your ./public/ folder? If not, you need to tell browserSync what is your start page. You can also get browserSync to show the listing of the base directory, see update below.
You could also try to use public without the leading dot.
Edit: The startPath config directive does not seem to work, use index instead
...
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "public/",
index: "my-start-page.html"
}
});
});
...
Update: Actually you can get directory listing with browserSync. That way it would show a list of files in public, not the Cannot Get error
...
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "public/",
directory: true
}
});
});
...
I got this to work when the index.html file was inside the same folder:
browserSync.init({
server: {
baseDir: "./"
}
});
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
},
port: 8080,
open: true,
notify: false
});
});
gulp.task('serve',['sass'], function() {
bs.init({
server: "./app",
startPath: "/index.html", // After it browser running
browser: 'chrome',
host: 'localhost',
port: 4000,
open: true,
tunnel: true
});
I solved my "Cannot GET" errors in browser-sync by always pointing to a .html file in code, or by having a folder structure ending with and index.html
About <!-- Cannot GET error-->
About <!-- same code as above, but works if your site structure is: ./about/index.html-->
About <!-- OK -->
My Gulp file for reference (using browser-sync with jekyll, so everything is in the ./_site folder, and the gulpfile is in ./)
var gulp = require('gulp');
var shell = require('gulp-shell');
var browserSync = require('browser-sync').create();
gulp.task('build', shell.task(['jekyll build --watch']));
// serving blog with Browsersync
gulp.task('serve', function () {
browserSync.init(
{
server: {baseDir: '_site/'}
}
);
// Reloads page when some of the already built files changed:
gulp.watch('_site/**/*.*').on('change', browserSync.reload);
});
gulp.task('default', ['build', 'serve']);
Hope it helps.
Michelangelo
May be you have not index.html in baseDir: '_site/'? In order to see your static web-page in the web-browser instead of that annoying message you have to rename a file your_file.html to index.html. This will solve Cannot GET/ problem.
In my case, this helped me:
server: {
baseDir: '.',
index: "index.html"
}
gulp.task('server', function()
{
browserSync.init(["public/src/css/","public/src/js"],{
server: "./",
startPath: "./index.html", // After it browser running
// browser: 'chrome',
host: 'localhost',
// port: 4000,
open: true,
tunnel: true });
});
gulp.task('default', ['scripts', 'styles', 'html', 'server', 'watch']);
In my build process I want to put the artifacts of the build steps into .tmp/serve directory.
I managed to set up gulp-watch to fire specific tasks when I modify files in my working directory. E.q. when I modify htmls, they are built and the artifacts are pasted into desired .tmp/serve directory
I'm having problems with reloading the files from .tmp/serve with browser-sync. When I save changes in my working directory multiple times, browser-sync refreshes only the previous changes (1 change delay). I guess the reload function fires before gulp-dest finishes. Note that if I refresh browser manually the current changes appear.
Am I doing something wrong?
Build htmls task
gulp.task('html', ['styles'], () => {
return gulp.src('app/*.html')
.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
.pipe(gulp.dest('.tmp/serve'))
;
});
Sever task
const reload = browserSync.reload;
gulp.task('serve', ['styles', 'fonts', 'build:scripts', 'html', 'images'], () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp/serve'],
routes: {
'/bower_components': 'bower_components'
}
}
});
/*********** SEE THE LINES BELOW **************/
gulp.watch([
'.tmp/serve/**/*',
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('app/*.html', ['html']);
gulp.watch('app/scripts/**/*', ['build:scripts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
You can use run-sequence to reload after a build.
Your gulpfile would become like this..
var gulp = require('gulp'),
runSeq = require('run-sequence')
...
;
gulp.task('build', ['styles', 'fonts', 'build:scripts', 'html', 'images']);
gulp.task('serve', ['build', 'watch'], () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp/serve'],
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.task('reload', function (callback) {
browserSync.reload();
callback();
});
gulp.task('watch', ['watch-styles', ...]);
gulp.task('watch-styles', function () {
gulp.watch('app/styles/**/*.scss', function () {
runSeq('styles', 'reload');
});
});
/* And so on for every watch task */
Note that run-sequence needs your tasks to either return a stream or to call a callback, otherwise it will cause gulp to pause indefinitely. Read the Doc to learn more.
I've used Gulp a number of times but this problem has me totally stumped. I have a render task to save an HTML template piped through gulp-swig. It works perfectly fine when invoked manually via gulp render but will not save when the task is triggered by gulp.watch. So, to clarify, the watcher does trigger the task but the rendered file doesn't actually get saved to its destination.
I've boiled the problem down to the following, removing all other tasks from my gulpfile, axed plumber, context data, etc. Any help appreciated!
var gulp = require( 'gulp' ),
browserSync = require( 'browser-sync' ).create(),
rename = require( 'gulp-rename' ),
swig = require( 'gulp-swig' ),
reload = browserSync.reload;
gulp.task( 'render', function() {
return gulp.src( './dev/template.html' )
.pipe( swig() )
.pipe( rename( 'index.html' ) )
.pipe( gulp.dest( './preview' ) )
.on( 'end', reload );
});
gulp.task( 'serve', function() {
browserSync.init( { server: './preview' } );
gulp.watch( './dev/*.html', [ 'render' ] );
});
gulp.task( 'default', [ 'serve' ] );
Duh, got it working. It appears that swig caches the template by default (?) so it was in fact saving the file but it was identical. I noticed a 'cache' option in another (unrelated) post about swig which did the trick. So, I needed to pass in an options object, like so:
.pipe( swig({
defaults: { cache: false }
}) )