Gulp acting differently on remote server - node.js

I run the same gulpfile on local and remote. On local, everything is fine but when on remote, both "vendors" and "assets" tasks are not doing anything and there's no error when I run the gulp. Below is my gulp script -
var gulp = require('gulp'),
gutil = require('gulp-util'),
clean = require('gulp-clean'),
changed = require('gulp-changed'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
less = require('gulp-less'),
csso = require('gulp-csso'),
jade = require('gulp-jade'),
es = require('event-stream'),
embedlr = require('gulp-embedlr'),
refresh = require('gulp-livereload'),
express = require('express'),
http = require('http'),
lr = require('tiny-lr')();
gulp.task('clean', function () {
// Clear the destination folder
gulp.src('dist/**/*.*', { read: false })
.pipe(clean({ force: true }));
});
// Vendor Files
// var vendors = {
// js: [ './bower_components/**/ZeroClipBoard.js'],
// assets: ['./bower_components/**/ZeroClipBoard.swf']
// };
// Compile JS
gulp.task('scripts', function () {
return es.concat(
// Detect errors and potential problems in your JavaScript code
// You can enable or disable default JSHint options in the .jshintrc file
// Concatenate, minify and copy all JavaScript (except vendor scripts)
gulp.src(['./src/js/**/*.js'])
.pipe(concat('main.js'))
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('./dist/js'))
.pipe(refresh(lr))
)});
// Copy Vendor Script and Assets
gulp.task('assets', function () {
return gulp.src(['./bower_components/**/ZeroClipBoard.swf'], {base: './'})
.pipe(gulp.dest('./dist/vendors'));
});
gulp.task('vendors', function () {
return gulp.src(['./bower_components/**/ZeroClipBoard.js'])
.pipe(concat('vendor.js'))
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('./dist/js'));
});
// Compile LESS files
gulp.task('styles', function () {
return gulp.src('./src/less/styles.less')
.pipe(less())
.pipe(rename('styles.css'))
.pipe(csso())
.pipe(gulp.dest('./dist/css'))
.pipe(refresh(lr));
});
gulp.task('templates', function () {
// Compile Jade files
return gulp.src('./src/jade/index.jade')
.pipe(jade())
.pipe(rename('index.html'))
.pipe(gulp.dest('./dist/'))
.pipe(refresh(lr));
});
gulp.task('server', function () {
// Create a HTTP server for static files
var port = 3000;
var app = express();
var server = http.createServer(app);
app.use(express.static(__dirname + '/dist'));
server.on('listening', function () {
gutil.log('Listening on http://localhost:' + server.address().port);
});
server.on('error', function (err) {
if (err.code === 'EADDRINUSE') {
gutil.log('Address in use, retrying...');
setTimeout(function () {
server.listen(port);
}, 1000);
}
});
server.listen(port);
});
gulp.task('lr-server', function () {
// Create a LiveReload server
lr.listen(35729, function (err) {
if (err) {
gutil.log(err);
}
});
});
gulp.task('watch', function () {
// Watch .less files and run tasks if they change
gulp.watch('./src/less/**/*.less', ['styles']);
// Watch .jade files and run tasks if they change
gulp.watch('./src/jade/index.jade', ['templates']);
// Watch .js files
gulp.watch('./src/js/**/*.js', ['scripts']);
});
// The dist task (used to store all files that will go to the server)
gulp.task('dist', ['clean', 'styles', 'templates', 'scripts', 'vendors']);
// The default task (called when you run `gulp`)
gulp.task('default', ['clean', 'styles', 'templates', 'scripts', 'assets', 'vendors', 'lr-server', 'server', 'watch']);

Related

Gulp and Browsersync injecting CSS but causing a full reload

I am trying to configure Gulp and Browsersync to inject CSS changes without a reload. The attached Gulpfile.js is calling .pipe(browserSync.stream()) after the SASS task. We see it inject, but then calls a full reload.
/**
* Gulpfile
*/
var gulp = require('gulp');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var notify = require('gulp-notify');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var fs = require("fs");
var exec = require('child_process').exec;
var config = require("./config");
var appDir = 'web'
/**
* If config.js exists, load that config for overriding certain values below.
*/
function loadConfig() {
if (fs.existsSync(__dirname + "/./config.js")) {
config = {};
config = require("./config");
}
return config;
}
loadConfig();
/*
* This task generates CSS from all SCSS files and compresses them down.
*/
gulp.task('sass', function () {
return gulp.src(appDir + '/anonymous/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
noCache: true,
outputStyle: "compressed",
lineNumbers: false,
loadPath: appDir + '/anonymous/css/*',
sourceMap: true
})).on('error', function(error) {
gutil.log(error);
this.emit('end');
})
.pipe(sourcemaps.write(appDir + '/anonymous/maps'))
.pipe(gulp.dest(appDir + '/anonymous/css'))
.pipe(browserSync.stream())
.pipe(notify({
title: "SASS Compiled",
message: "All SASS files have been recompiled to CSS.",
onLast: true
}))
;
});
/**
* Define a task to spawn Browser Sync.
* Options are defaulted, but can be overridden within your config.js file.
*/
gulp.task('browser-sync', function() {
browserSync.init({
port: config.browserSync.port,
proxy: config.browserSync.hostname,
open: config.browserSync.openAutomatically,
injectChanges: config.browserSync.injectChanges
});
});
/**
* Defines the watcher task.
*/
gulp.task('watch', function() {
// watch scss for changes
gulp.watch([
appDir + '/anonymous/scss/**/*.scss',
appDir + '/secure/components/**/*.scss'
], ['sass']);
});
gulp.task('default', [
'sass',
'watch',
'browser-sync'
]);
Here is the config.js that is referenced in the browsersync config.
module.exports = {
browserSync: {
hostname: "http://192.168.50.4:9080/site/secure",
port: 3000,
openAutomatically: true,
reloadDelay: 50,
injectChanges: true,
},
};
I figured out the answer to my own question.
There is a source map being generated and browsersync is watching the sourcemap folder and triggering a full refresh when the sourcemap is regenerated. Removing these lines stops the full refresh on the SASS task.
.pipe(sourcemaps.init())
.pipe(sourcemaps.write(appDir + '/anonymous/maps'))
Reference
https://github.com/BrowserSync/browser-sync/issues/235

gulp sass source map

I need help adding source map to SASS compiler in the same CSS output folder. Till now, I got to install gulp-sourcemaps module within gulpfile.js but couldn't know success to bind sourcemaps.write as gulp.task.
Any help is much appreciated :)
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var bs = require('browser-sync').create();
gulp.task('browser-sync', ['sass'], function() {
bs.init({
server: {
baseDir: "./"
},
proxy: {
target: "localhost:8080", // can be [virtual host, sub-directory, localhost with port]
ws: true // enables websockets
}
});
});
gulp.task('sass', function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('assets/css'))
.pipe(bs.reload({
stream: true
}));
});
gulp.task('watch', ['browser-sync'], function () {
gulp.watch("scss/*.scss", ['sass']);
gulp.watch("*.php").on('change', bs.reload);
});
Try this code for gulp task 'sass':
gulp.task('sass', function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('assets/css'))
.pipe(bs.reload({
stream: true
}));
});
First init sourcemaps then compile sass() after that write sourcemap in the same folder ('.')
Regards
I'm using this task since 5 months everyday and works fine,
const gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
var sassSourcePath = 'YourPath/scss/**/*.scss',
cssDestPath = 'YourPath/css/';
gulp.task('sass', () => {
return gulp
.src(sassSourcePath)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(sourcemaps.write({includeContent: false}))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(autoprefixer({ browser: ['last 2 version', '> 5%'] }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(cssDestPath));
});
Also recommend you the require('gulp-csso') for the production version
A complete solution for gulp-sass, map, count all files, minify:
./sass/partial_folders/index.scss
#import 'base/_reset';
#import 'helpers/_variables';
#import 'helpers/_mixins';
#import 'helpers/_functions';
#import 'base/_typography';
etc..
./gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('default', function(){
gulp.watch('sass/**/*.scss', ['styles']);
})

node.js gulp-livereload not refreshing in browser

I am new to node.js. With the following code the reload task is triggered when files in the dist folder are modified.
I have the livereload plugin in chrome activated. The status is "live reload is connected". Yet the browser is not refreshed automatically.
Anything missing in this code?
const path = require('path');
const gulp = require('gulp');
const nodemon = require('gulp-nodemon');
const es6Pipeline = require('gulp-webpack-es6-pipeline');
const less = require('gulp-less');
var webserver = require('gulp-webserver');
var livereload = require('gulp-livereload');
es6Pipeline.registerBuildGulpTasks(
gulp,
{
entryPoints: {
'bundle': path.join(__dirname, '/src/index.js')
},
outputDir: path.join(__dirname, 'public/generated/js')
}
);
gulp.task('live-server', (done) => {
});
gulp.task('test-server', function () {
var express = require('express'),
serverport = 5000;
var server = express();
server.use(express.static('./dist'));
server.listen(serverport);
console.log("Server started at port: " + serverport);
// Start live reload
livereload({start: true});
gulp.watch('dist/*.*', ['reload']);
});
gulp.task('reload', function () {
console.log("refreshed");
livereload();
});
gulp.task('generate', ['es6Pipeline:build:release']);
gulp.task('run-release', ['es6Pipeline:build:release', 'test-server']);
gulp.task('run-dev', ['es6Pipeline:build:dev', 'test-server']);
gulp.task('default', ['es6Pipeline:watch', 'test-server']);
Have you tried the following ?
gulp.task('reload', function () {
console.log("refreshed");
livereload.listen();
});

GulpJS not running on port defined on app.js expressjs

i had setup some gulp tasks and started gulp but gulp is running on port 3000 and my app config is to listen on port 4545 so it opens 3000 port but no any contents it displays output like Cannot GET /.
my project stucture is like
controllers
views
public
app.js
gulpfile.js
so i want gulp to listen on port defined in app.js and watch changes on public flder.
I have included gulp plugin like gulp-plumber,gulp-browser-sync
and its my gulpfile.js
var gulp = require('gulp'),
browserSync = require('browser-sync'),
reload = browserSync.reload,
plumber = require('gulp-plumber')
gulp.task('scripts', function() {
return gulp.src('public/javascripts/**/*.js')
.pipe(plumber())
.pipe(reload({
stream: true
}));
});
gulp.task('styles', function() {
gulp.src('public/stylesheets/**/*.css')
.pipe(plumber())
.pipe(reload({
stream: true
}));
});
// gulp.task('html', function() {
// gulp.src('app/**/*.html')
// .pipe(reload({
// stream: true
// }));
// });
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
gulp.task('watch', function() {
gulp.watch('public/javascripts/**/*.js', ['styles']);
gulp.watch('public/stylesheets/**/*.css', ['scripts']);
});
gulp.task('default', ['scripts', 'styles', 'browser-sync', 'watch']);
You can use gulp-nodemon
var gulp = require('gulp'),
nodemon = require('gulp-nodemon')
gulp.task('develop', function () {
nodemon({
script: 'app.js',
ext: 'js',
}).on('restart', function () {
// a server restarted hook can be added here
});
});
gulp.task('default', ['develop']);
Basically it will restart automatically the server when you change a js file

Setup/teardown of express.js application with mocha

I'm trying to create a standalone test suite using mocha, that in a perfect world would start up my express.js application, use zombie to render a page, check a bunch of stuff and then teardown/kill the express.js application.
Is there an easy/best way to do this?
NB. I could just have the express application server running prior to running the tests, but what good are Yaks if you're not going to shave them.
First, you need to move your actual app setting up into a module, and import that into the file that actually starts your app. Now that this is seperate, you can have the app in its complete state before actually listening.
You should move the actual setting up of your app into a separate file, let's call it app.js, can call listen from the file you run node off of, let's call it index.js.
So, app.js would look like:
var express = require('express')
, routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
and index.js would look like:
var app = require('./app');
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
This seperates loading of your app from actually having it listen, allowing you to load that app into your unit tests.
In your unit tests, you would do something in a setup method and teardown method to bring up and bring down the server.
In the file test/app_tests.js:
describe('app', function(){
var app = require('../app');
beforeEach(function(){
app.listen(3000);
});
// tests here
afterEach(function(){
app.close();
})
});
In addition to Oved D answer.
Describe your app in express-app.js or some other file:
module.exports = function (o) {
o = o || {};
var app = express();
// app.configure
// configure routes
if (o.someOption) {
// some additional test code
}
return app;
}
describe tests in test/01-some.js:
var expressApp = require('../express-app');
describe('some', function () {
// just describe needed vars
var app, server, port;
// describe setup
before(function (next) {
// create app when
app = expressApp({routes: /api\/some\/.*/ /* put here some test options ...*/});
// creating listener with random port
server = app.listen(function () {
// store port when it ready
port = server.address().port;
// and go to tests
next();
});
});
// tests
it('should return valid result', function (done) {
// do a simple request to /api/some
http.request({
host: 'localhost',
port: port,
path: '/api/some'
}, function (res) {
if (res.err) throw new Error(res.err);
done();
});
});
// teardown
after(function () {
// stop listening that port
server.close();
});
});
Done. ;-)
Now you can create any count of tests like that. Recommend you to enable only needed urls and services in tests with defining it by passing params to express-app.js module.
Update:
Not sure how it works in mocha but better to move before and after calls to init.js and load it with mocha --require init.js.
File should looks like that:
// use it in your mocha tests
global.setupEnv = function setupEnv (o, before, after) {
// just describe needed vars
var env = Object.create(null);
// setup
before(function (next) {
// create app
env.app = expressApp(o);
// creating listener with random port
env.server = env.app.listen(function () {
// store port when it ready
port = env.server.address().port;
env.app.log('Listening on ', env.port);
// and go to tests
next();
});
});
// teardown
after(function () {
// stop listening that port
env.server.close();
});
return env;
}
And in your tests:
// requiring dependencies
var request = require('request');
describe('api', function () {
// describe setup
var env = global.setupEnv({
routes: 'api/some'
}, before, after);
// tests
it('should pass', function (done) {
request('http://localhost:' + env.port, function (error, response, body) {
done();
});
});
});

Resources