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?
Related
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();
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);
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']);
});
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'
};
I'm working on a mean.io
server.js
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
fs = require('fs'),
passport = require('passport'),
logger = require('mean-logger');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
//Load configurations
//Set the node enviornment variable if not set before
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
//Initializing system variables
var config = require('./config/config'),
auth = require('./config/middlewares/authorization'),
mongoose = require('mongoose');
//Use only for development env
if (process.env.NODE_ENV === 'development') {
//mongoose.set('debug', true);
}
// set temp directory for uploads
process.env.TMPDIR = config.tmp;
//Bootstrap db connection
var db = mongoose.connect(config.db);
//Bootstrap models
var modelsPath = __dirname + '/app/models';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(newPath);
}
} else if (stat.isDirectory()) {
walk(newPath);
}
});
};
walk(modelsPath);
//bootstrap passport config
require('./config/passport')(passport);
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
//express settings
require('./config/express')(app,passport,db);
//Bootstrap routes
require('./config/routes')(app,passport,auth);
//Start the app by listening on <port>
var port = process.env.PORT || config.port;
server.listen(port);
io.sockets.on('connection', function (socket){
socket.on('addPost', function (data) {
socket.broadcast.emit('addedPost', data);
});
});
console.log('Express app started on port ' + port);
//Initializing logger
logger.init(app,passport ,mongoose);
//expose app
exports = module.exports = app;
routes.js
var postController = require('../app/controllers/api/post');
app/controllers/api/post.js
exports.upload = function(req, res,next) {
var w = 200;
var h = 75;
var form = new formidable.IncomingForm;
form.on('progress', function(bytesReceived, bytesExpected){
var percent = Math.floor(bytesReceived / bytesExpected * 100);
// here is where you can relay the uploaded percentage using Socket.IO
// How can got socket here !
socket.emit('progress', { percent: percent });
});
form.parse(req, function(err, fields, files){
if(err){
res.jsonp(500, err.message);
}
});
};
I don't find the way to get socket
in exports.upload any ideas ?