Auto reload in browsersync not working - browser-sync

I tried many variant of code but the home.html load only once and it does not reload automatically when I change Style.css file in css folder.
I tried this
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload()
gulp.task('serve', function () {
browserSync.init({
server: {
baseDir: "./",
index: "./main/home.html"
},
});
gulp.watch("/css/Style.css", [reload])
});
And
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload("./main/home.html")
gulp.task('serve', function () {
browserSync.init({
server: {
baseDir: "./",
index: "./main/home.html"
},
});
gulp.watch("/css/Style.css", [reload])
});
And
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('serve', function () {
browserSync.init({
server: {
baseDir: "./",
index: "./main/home.html"
},
});
gulp.watch("./css/Style.css").on("change", browserSync.reload);
});
Any idea please what I am doing wrong?

Change this:
var reload = browserSync.reload()
to
var reload = browserSync.reload;
and your third version should work with the change below:
gulp.watch("./css/Style.css").on("change", reload);

Related

Gulp + Browserify no output

i have the following code for my gulpfile.js
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var jsEntry = './src/_Cwp/assets/PTM/scripts/main.js';
var jsDist = './dist/js';
gulp.task('js', function(){
return browserify({
entries: [jsEntry],
debug: true,
paths: ['./node_modules','./src/_modules/', './src/Cwp/assets/PTM/scripts/', './src/_Cwp/assets/PTM/scripts/']
})
.transform(babelify)
.bundle()
.pipe(source('main.js'))
.pipe(rename({extname: '.min.js'}))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(jsDist))
});
When I run gulp js in the terminal, nothing happens:
Any particular reason as to why is the cause for this?

Node + Gulp - Have to save files two times to see changes in browser

Could you please point me in the right direction to solve this inconsistence?
I'm working in a new project using Node, gulp and a list of gulp's plugins.
Everytime I do Ctrl + S the browser does reload but I don't see the changes applied so I need to Ctrl + S again to see them. This second time the browser reloads again displaying the changes.
This is happening with any of my html, scss or js files under my source directory.
I'm working on Windows 10 using Visual Studio Code and everything works fine except for this.
My gulpfile.js content is the following:
var gulp = require('gulp');
var sass = require('gulp-sass');
var inject = require('gulp-inject');
var wiredep = require('wiredep').stream;
var plumber = require('gulp-plumber');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync');
var uglify = require('gulp-uglify');
gulp.task('styles', function(){
var injectFiles = gulp.src(['!src/styles/main.scss', 'src/styles/*.scss'], {read: false});
var injectGlobalFiles = gulp.src('src/global/*.scss', {read: false});
function transformFilepath(filepath) {
return '#import "' + filepath + '";';
}
var injectFilesOptions = {
transform: transformFilepath,
starttag: '// inject:app',
endtag: '// endinject',
addRootSlash: false
};
var injectGlobalOptions = {
transform: transformFilepath,
starttag: '// inject:global',
endtag: '// endinject',
addRootSlash: false
};
return gulp.src('src/styles/main.scss')
.pipe(plumber())
.pipe(wiredep())
.pipe(inject(injectGlobalFiles, injectGlobalOptions))
.pipe(inject(injectFiles, injectFilesOptions))
.pipe(sass())
.pipe(gulp.dest('dist/styles'));
});
gulp.task('browser-sync', function() {
browserSync.init(["styles/*.css", "js/*.js","index.html"], {
server: {
baseDir: "dist"
}
});
});
gulp.task('html', ['styles'], function(){
var injectFiles = gulp.src('src/styles/*.scss', {read: false});
var injectOptions = {
addRootSlash: false,
ignorePath: ['src', 'dist']
};
return gulp.src('src/index.html')
.pipe(plumber())
.pipe(inject(injectFiles, injectOptions))
.pipe(gulp.dest('dist'));
});
gulp.task('imagemin', function() {
gulp.src('src/assets/*.{jpg,jpeg,png,gif,svg}')
.pipe(plumber())
.pipe(imagemin())
.pipe(gulp.dest('dist/assets'));
});
gulp.task('uglify', function() {
gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
gulp.task('sass', function() {
gulp.src('src/styles/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('dist/styles/'));
});
gulp.task('watch', function() {
gulp.watch('src/js/*.js', ['uglify']).on('change', browserSync.reload);
gulp.watch('src/styles/*.scss', ['sass']).on('change', browserSync.reload);
gulp.watch('src/assets/*.{jpg,jpeg,png,gif,svg}', ['imagemin']).on('change', browserSync.reload);
gulp.watch('src/index.html', ['html']).on('change', browserSync.reload);
});
gulp.task('default', ['html', 'sass','imagemin', 'uglify', 'browser-sync', 'watch']);
Any help will be very appreciated.
Thank you and have a good one.
Try these changes:
var browserSync = require('browser-sync').create();
gulp.task('watch', function() {
gulp.watch('src/js/*.js', ['uglify']).on('change', browserSync.reload({ stream:true }));
gulp.watch('src/styles/*.scss', ['sass']).on('change', browserSync.reload({ stream:true }));
gulp.watch('src/assets/*.{jpg,jpeg,png,gif,svg}', ['imagemin']).on('change', browserSync.reload);
gulp.watch('src/index.html', ['html']).on('change', browserSync.reload());
});
If that doesn't help, I would move the reload calls to the end of each task like this :
.pipe(browserSync.reload({ stream:true }));
Hope this helps.
[EDIT]
Change to this:
gulp.task('watch', function() {
gulp.watch('src/js/*.js', ['uglify']);
gulp.watch('src/styles/*.scss', ['sass']);
gulp.watch('src/assets/*.{jpg,jpeg,png,gif,svg}', ['imagemin']);
gulp.watch('src/index.html', ['html']).on('change', browserSync.reload);
});
gulp.task('imagemin', function() {
return gulp.src('src/assets/*.{jpg,jpeg,png,gif,svg}')
.pipe(plumber())
.pipe(imagemin())
.pipe(gulp.dest('dist/assets'));
.pipe(browserSync.reload({ stream:true }));
});
gulp.task('uglify', function() {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
.pipe(browserSync.reload({ stream:true }));
});
gulp.task('sass', function() {
return gulp.src('src/styles/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('dist/styles/'));
.pipe(browserSync.reload({ stream:true }));
});
The other parts of your gulpfile don't change. Except do make the previously suggested change:
var browserSync = require('browser-sync').create();

gulpfile: Task 'default' is not in your gulpfile , with a default does not watch

I have a simple gulp file that when i have no default task it gives me an error, but when i add a default task it does not watch.
here is what I have in the file:
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task( 'default', ['sass'] );
gulp.task('sass', function () {
return gulp.src('./sass/theme.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
You can achieve this with gulpfile like this:
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('default', ['watch']);
gulp.task('sass', function () {
return gulp.src('./sass/theme.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('watch', ['sass'], function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});

gulp inject not working properly

I am using gulp inject command to add my css and js files to the html page. When I am checking the file the file are injected but when I run the html page it shows file not found and it doesn`t load the files.
This is gulp file -
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var nodemon = require('gulp-nodemon');
var jsFiles = ['*.js','src/**/*.js'];
gulp.task('style',function(){
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish',{
verbose: true
}));
});
gulp.task('inject',function(){
var wiredep = require('wiredep').stream;
var inject = require('gulp-inject');
var injectSrc = gulp.src([__dirname + '/public/css/*.css',__dirname + '/public/js/*.js'],{read: false});
var injectOptions = {
ignorePath: '../..public'
};
var options = {
bowerJson: require(__dirname + '/node_modules/bower/lib/node_modules/qs/bower.json'),
directory: './public/lib',
ignorePath: '../../public'
}
return gulp.src('./src/views/*.html')
.pipe(wiredep(options))
.pipe(inject(injectSrc,injectOptions))
.pipe(gulp.dest('./src/views'));
});
gulp.task('serve', ['style','inject'], function(){
var options = {
script: 'app.js',
delayTime: 1,
env:{
'PORT': 3000
},
watch: jsFiles
}
return nodemon(options)
.on('restart',function(ev){
console.log('Restarting....');
})
})
This is my app.js -
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
//app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/src/views'));
app.get('/',function(req,res){
res.send('Hello World');
});
app.get('/books',function(req,res){
res.send('Hello Books');
});
app.listen(port,function(err){
console.log('running server on port'+ port);
});
But still files not getting loaded on my html page.
Can anyone help me in understanding what the problem is?
Files injected in html page:
Fixed the issue.
changed the line-
var injectOptions = {
ignorePath: '../..public'
};
to this-
var injectOptions = {
ignorePath: '/public'
};

Cannot connect to Node.js server using socket.io + express + webpack, requests return 404 errors

I am trying to test my first socket.io server/client codes. But it failed.
My HTML file is like this:
<html>
<body>
<h1>Welcome to socket project</h1>
<div id="result"></div>
<script src="https://cdn.socket.io/socket.io-1.4.8.js"></script>
<script src="./dist/main.bundle.js"></script>
</body>
</html>
My client side code is like this:
const socket = io.connect('http://localhost:9999');
console.log('Connected: ', socket.connected);
socket.emit('setPlayerPosition', {
reason: 'It\'s my birthday'
});
My server code is like this:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.base');
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer();
const io = require('socket.io')(server);
const port = 9999;
const devPort = port - 1;
const domain = 'http://127.0.0.1:' + devPort;
const devServer = new WebpackDevServer(webpack({
devtool: 'eval',
entry: {
main: [
'webpack/hot/only-dev-server',
`webpack-dev-server/client?${domain}`,
config.entry.main
]
},
output: config.output,
plugins: config.plugins.concat([
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]),
module: config.module,
resolve: config.resolve,
}), {
publicPath: `${domain}/`,
hot: true,
historyApiFallback: true,
port: devPort,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
});
io.on('connection', function(socket) {
socket.on('setPlayerPosition', function(id, msg) {
console.log('Position' + msg.reason);
socket.broadcast.to(id).emit('serverMsg', {
msg: 'hello'
});
});
});
app.use('/static', express.static(__dirname + '/media'));
// app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.end(
fs.readFileSync('./public/index.html')
.toString()
.replace(/\.\/dist\//g, `${domain}/`)
);
});
app.listen(port, function() {
console.log('Server is running on port', port);
});
devServer.listen(devPort);
I can connect with http but when I use socket.io it gives me a 404 error.
Failed to load resource: the server responded with a status of 404 (Not Found), the client side console log is "Connected: false".
How to resolve this problem?
You're creating an HTTP server to host the socket.io server:
const server = require('http').createServer();
const io = require('socket.io')(server);
However, you're not calling .listen() on that server instance, so it won't be listening on port 9999 as you might expect.
Here's an alternative setup that should work:
const port = 9999;
const app = express();
const server = app.listen(port, function() {
console.log('Server is running on port', port);
});
const io = require('socket.io')(server);

Resources