Prevent gulp to minify code on local machine - angularjs

I started a project with [RDash angular dashboard][1] which using gulp.
this is the first time I work with gulp and the problem is that while I'm working locally I can't debug because it minify css/js/html files.
How can I prevent from gulp to minify while working locally?
Here is what I have on gulpfile.js:
var gulp = require('gulp'),
usemin = require('gulp-usemin'),
wrap = require('gulp-wrap'),
connect = require('gulp-connect'),
watch = require('gulp-watch'),
minifyCss = require('gulp-minify-css'),
minifyJs = require('gulp-uglify'),
concat = require('gulp-concat'),
less = require('gulp-less'),
rename = require('gulp-rename'),
minifyHTML = require('gulp-minify-html');
var paths = {
scripts: 'src/js/**/*.*',
styles: 'src/less/**/*.*',
images: 'src/img/**/*.*',
templates: 'src/templates/**/*.html',
index: 'src/index.html',
bower_fonts: 'src/components/**/*.{ttf,woff,eof,svg}',
};
/**
* Handle bower components from index
*/
gulp.task('usemin', function() {
return gulp.src(paths.index)
.pipe(usemin({
js: [minifyJs(), 'concat'],
css: [minifyCss({keepSpecialComments: 0}), 'concat'],
}))
.pipe(gulp.dest('dist/'));
});
/**
* Copy assets
*/
gulp.task('build-assets', ['copy-bower_fonts']);
gulp.task('copy-bower_fonts', function() {
return gulp.src(paths.bower_fonts)
.pipe(rename({
dirname: '/fonts'
}))
.pipe(gulp.dest('dist/lib'));
});
/**
* Handle custom files
*/
gulp.task('build-custom', ['custom-images', 'custom-js', 'custom-less', 'custom-templates']);
gulp.task('custom-images', function() {
return gulp.src(paths.images)
.pipe(gulp.dest('dist/img'));
});
gulp.task('custom-js', function() {
return gulp.src(paths.scripts)
.pipe(minifyJs())
.pipe(concat('dashboard.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('custom-less', function() {
return gulp.src(paths.styles)
.pipe(less())
.pipe(gulp.dest('dist/css'));
});
gulp.task('custom-templates', function() {
return gulp.src(paths.templates)
.pipe(minifyHTML())
.pipe(gulp.dest('dist/templates'));
});
/**
* Watch custom files
*/
gulp.task('watch', function() {
gulp.watch([paths.images], ['custom-images']);
gulp.watch([paths.styles], ['custom-less']);
gulp.watch([paths.scripts], ['custom-js']);
gulp.watch([paths.templates], ['custom-templates']);
gulp.watch([paths.index], ['usemin']);
});
/**
* Live reload server
*/
gulp.task('webserver', function() {
connect.server({
root: 'dist',
livereload: true,
port: 8888
});
});
gulp.task('livereload', function() {
gulp.src(['dist/**/*.*'])
.pipe(watch())
.pipe(connect.reload());
});
/**
* Gulp tasks
*/
gulp.task('build', ['usemin', 'build-assets', 'build-custom']);
gulp.task('default', ['build', 'webserver', 'livereload', 'watch']);

You should add gulp-minify and use it as follows:
var minify = require('gulp-minify');
gulp.task('compress', function() {
gulp.src('lib/*.js')
.pipe(minify({
exclude: ['tasks'],
ignoreFiles: ['.combo.js', '-min.js']
}))
.pipe(gulp.dest('dist'))
});
Pass the files that you dont want to minify to the exclude.
In your code, you have specified that you want to minify all of the files here:
gulp.task('usemin', function() {
return gulp.src(paths.index)
.pipe(usemin({
js: [minifyJs(), 'concat'],
css: [minifyCss({keepSpecialComments: 0}), 'concat'],
}))
.pipe(gulp.dest('dist/'));
});
In line
.pipe(usemin({..})
Just dont use this usemin task, and you should be fine

Related

gulp watch resulting in an endless loop after upgrading to gulp 4

I have upgraded my gulpfile.js to gulp 4. gulp dev is working fine. But whenever I am editing any file the reload and inject tasks are entering into an endless loop.
My gulpfile.js:
var gulp = require('gulp'),
sass = require('gulp-sass'),
symlink = require('gulp-symlink'),
jshint = require('gulp-jshint'),
browserSync = require('browser-sync').create(),
concat = require('gulp-concat'),
useref = require('gulp-useref'),
replace = require('gulp-replace'),
templateCache = require('gulp-angular-templatecache'),
gulpif = require('gulp-if'),
gulpUtil = require('gulp-util'),
uglify = require('gulp-uglify'),
minifyCss = require('gulp-clean-css'),
merge = require('merge-stream'),
clean = require('gulp-clean'),
inject = require('gulp-inject'),
svgSprite = require('gulp-svg-sprite'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer');
webfonts = require('gulp-font');
/* DEV */
gulp.task('dev-serve', function () {
browserSync.init({
server: './'
});
gulp.watch('app/**/*.scss', gulp.parallel('sass'));
gulp.watch('app/**/*.html', gulp.series('inject', 'reload'));
gulp.watch('app/**/*.js', gulp.parallel('inject', 'reload'));
gulp.watch('app/images/svg-sprite/*', gulp.parallel('svg-sprite', 'reload'));
gulp.watch('app/images/**/*', gulp.parallel('reload'));
gulp.watch('app/fonts/*', gulp.parallel('reload'));
});
/* PROD */
gulp.task('prod-serve', function () {
browserSync.init({
server: './www'
});
gulp.watch('app/**/*.scss', gulp.parallel('sass', 'build-html'));
gulp.watch('app/**/*.html', gulp.parallel('inject', 'minify-scripts', 'reload'));
gulp.watch('app/**/*.js', gulp.parallel('inject', 'minify-scripts', 'reload'));
gulp.watch('app/images/**/*', gulp.parallel('copy-images', 'reload'));
gulp.watch('app/fonts/*', gulp.parallel('copy-fonts', 'reload'));
});
// SVG SPRITE
gulp.task('svg-sprite', function () {
var svgPath = 'app/images/svg-sprite/*.svg';
return gulp.src(svgPath)
.pipe(svgSprite({
shape: {
spacing: {
padding: 0
}
},
mode: {
css: {
dest: './',
layout: 'diagonal',
sprite: 'app/images/sprite.svg',
bust: false,
render: {
scss: {
dest: 'app/styles/tools/_sprite.scss',
template: 'app/styles/tools/_sprite-template.tpl'
}
}
}
},
variables: {
mapname: 'icons'
}
}))
.pipe(gulp.dest('./'));
});
// SCSS
gulp.task('sass', function (done) {
gulp.task('sass', function () {
return gulp.src('app/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(concat('style.css'))
.pipe(postcss([autoprefixer()]))
.pipe(gulp.dest('app'))
.pipe(browserSync.stream());
});
done();
});
// INJECT
gulp.task('inject', function () {
return gulp.src('app/index.html')
.pipe(inject(gulp.src(['app/**/*.module.js', 'app/**/*.js', '!app/vendor/**/*.js'], {read: false}), {relative: true}))
.pipe(gulp.dest('./app'));
});
// HTML
gulp.task('build-html', function () {
return gulp.src('app/index.html')
.pipe(replace('href="/app/"', 'href="/"')) // replace base href
.pipe(useref())
.pipe(gulpif('*.js', uglify().on('error', gulpUtil.log)))
.pipe(gulpif('*.css', minifyCss()))
.pipe(gulp.dest('www'));
});
// IMAGES
gulp.task('copy-images', function () {
return gulp.src(['app/images/*'])
.pipe(gulp.dest('www/images'));
});
// FONTS
gulp.task('copy-fonts', function () {
return gulp.src(['app/fonts/*'])
.pipe(gulp.dest('www/fonts'));
});
// TEMPLATES
gulp.task('bundle-templates', function () {
return gulp.src(['app/**/*.html', '!app/index.html'])
.pipe(gulpif('*.html', templateCache({module: 'jibbar'})))
.pipe(concat('templates.min.js'))
.pipe(gulp.dest('www/tmp'));
});
// COMPONENTS
gulp.task('bundle-components', function () {
return gulp.src(['app/**/*.module.js', 'app/**/*.js', '!app/vendor/**/*.js'])
.pipe(concat('script.min.js'))
.pipe(gulp.dest('www'));
});
// MERGE TEMPLATES AND COMPONENTS
gulp.task('merge-templates-and-components', gulp.parallel('bundle-templates', 'bundle-components'), function () {
return gulp.src(['www/script.min.js', 'www/tmp/templates.min.js'])
.pipe(concat('script.min.js'))
.pipe(gulp.dest('www'))
});
// MINIFY SCRIPTS
gulp.task('minify-scripts', gulp.parallel('merge-templates-and-components', 'bundle-templates', 'bundle-components'), function () {
return gulp.src('www/script.min.js')
.pipe(uglify().on('error', gulpUtil.log))
.pipe(gulp.dest('www'))
});
// CLEAN TEMP
gulp.task('clean', gulp.parallel('bundle-templates', 'bundle-components', 'merge-templates-and-components'), function () {
return gulp.src('www/tmp', {read: false})
.pipe(clean());
});
// RELOAD BROWSER
gulp.task('reload', gulp.series('inject'), function () {
browserSync.reload();
});
//COPY IFRAME
gulp.task('copy-iframe', function () {
return gulp.src('app/components/builder/iframe/*')
.pipe(gulp.dest('www/app/components/builder/iframe'));
});
//COPY TINYMCE
gulp.task('copy-tinymce', function () {
return gulp.src('app/vendor/tinymce/**/*')
.pipe(gulp.dest('www/app/vendor/tinymce'));
});
//COPY VENDOR FILES
gulp.task('copy-vendor-files', function () {
return gulp.src(['app/vendor/angular.js','app/vendor/bootstrap.css','app/vendor/tooltip.css','app/vendor/jquery.js'])
.pipe(gulp.dest('www/app/vendor'));
});
//COPY APP IMAGES
gulp.task('copy-app-images', function () {
return gulp.src(['app/images/builder-image.svg','app/images/builder-dimensions.svg','app/images/info_icon.svg'])
.pipe(gulp.dest('www/app/images'));
});
gulp.task('dev', gulp.series(
'inject',
'svg-sprite',
'sass',
'dev-serve'
));
gulp.task('prod', gulp.series(
'inject',
'sass',
'copy-iframe',
'copy-tinymce',
'copy-vendor-files',
'copy-app-images',
'build-html',
'copy-images',
'copy-fonts',
'minify-scripts',
'clean',
'prod-serve'
));
The following image shows the endless loop
Can anyone please help me to find out what I am doing wrong here.
Thanks in advance.
In addition to my comment above, this is probably a problem:
// RELOAD BROWSER
gulp.task('reload', gulp.series('inject'), function () {
browserSync.reload();
});
In your watch statements you call inject and reload, and then in the reload task you call inject first which updates your html files (timestamp if nothing else) and so the html watch is retiggered which calls inject and reload again, etc.
Just use:
// RELOAD BROWSER
gulp.task('reload', function () {
browserSync.reload();
});
and change all your watch's to gulp.series. Since you call reload last there is no need to call inject within the reload task again.
/* PROD */
gulp.task('prod-serve', function () {
browserSync.init({
server: './www'
});
gulp.watch('app/**/*.scss', gulp.series('sass', 'build-html'));
gulp.watch('app/**/*.html', gulp.series('inject', 'minify-scripts', 'reload'));
gulp.watch('app/**/*.js', gulp.series('inject', 'minify-scripts', 'reload'));
gulp.watch('app/images/**/*', gulp.series('copy-images', 'reload'));
gulp.watch('app/fonts/*', gulp.series('copy-fonts', 'reload'));
});
and do the same for your 'dev-serve' task.
[Edit to fix will only run once]
Change to:
// RELOAD BROWSER
gulp.task('reload', gulp.series('inject'), function (done) {
browserSync.reload();
done();
});
Also I'm pretty sure you need to use this form:
// RELOAD BROWSER
//--------------------------------------|
gulp.task('reload', gulp.series('inject', function (done) {
browserSync.reload();
done();
}));
// another ) at the end above too.
See how the last anonymous function is included in the gulp.series call. You need to make that change in quite a few of your tasks.

angular breaks after gulp-uglify and gulp-concat for controllers where I have used $uibModal

This is my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');
var del = require('del');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var htmlmin = require('gulp-htmlmin');
var ngAnnotate = require('gulp-ng-annotate');
var sourcemaps = require('gulp-sourcemaps');
var paths = {
html: {entry: ['public/angular/entry.html'], partials: ['public/angular/partials/**/*.html'], views: ['public/angular/views/**/*.html']},
dist: 'public/dist',
bower_components: ['bower_components/jquery/dist/jquery.min.js', 'bower_components/jquery.cookie/jquery.cookie.js', 'bower_components/bootstrap/dist/js/bootstrap.min.js', 'bower_components/jquery.nicescroll/jquery.nicescroll.min.js','bower_components/jquery-sparkline/dist/jquery.sparkline.min.js', 'bower_components/jquery.easing/jquery.easing.min.js', 'bower_components/bootbox.js/bootbox.js', 'bower_components/retina.js/dist/retina.min.js', 'bower_components/angular/angular.min.js', 'bower_components/angular-sanitize/angular-sanitize.min.js', 'bower_components/angular-touch/angular-touch.min.js', 'bower_components/angular-animate/angular-animate.min.js', 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'bower_components/oclazyload/dist/ocLazyLoad.min.js', 'bower_components/angular-ui-router/release/angular-ui-router.min.js', 'bower_components/angular-ui-router/release/stateEvents.min.js', 'bower_components/angular-loading-bar/build/loading-bar.min.js', 'bower_components/angular-ui-select/dist/select.js', 'bower_components/checklist-model/checklist-model.js'],
app_scripts: ['public/angular/scripts/app.js', 'public/angular/scripts/**/*.js'],
app_styles: ['public/angular/styles/reset.css', 'public/angular/styles/layout.css', 'public/angular/styles/components.css', 'public/angular/styles/plugins.css', 'public/angular/styles/themes/green-army.theme.css', 'public/angular/styles/custom.css', 'public/angular/styles/layout/header-loggedin.css', 'public/angular/styles/layout/header-loggedout.css', 'public/angular/styles/pages/sign-in.css', 'public/angular/styles/pages/pos.css', 'public/angular/styles/pages/brand.css', 'public/angular/styles/pages/products.css', 'public/angular/styles/pages/pricing.css', 'public/angular/styles/pages/landing-page.css', 'public/angular/styles/pages/company-profile.css', 'public/angular/styles/invoice-print.css', 'public/angular/styles/angular-custom.css'],
bower_components_styles: ['bower_components/bootstrap/dist/css/bootstrap.min.css', 'bower_components/font-awesome/css/font-awesome.min.css', 'bower_components/animate.css/animate.min.css', 'bower_components/angular-loading-bar/build/loading-bar.min.css', 'bower_components/angular-ui-select/dist/select.min.css', 'bower_components/angular-ui-select/dist/select.css', 'bower_components/angular-bootstrap/ui-bootstrap-csp.css']
};
gulp.task('clean', function () {
return del.sync([paths.dist]);
});
gulp.task('html', ['mainHtml', 'partialsHtml', 'viewsHtml'], function() {
console.log('copying html files started');
});
gulp.task('mainHtml', function() {
gulp.src(paths.html.entry)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(rename('index.html'))
.pipe(gulp.dest(paths.dist));
});
gulp.task('partialsHtml', function() {
gulp.src(paths.html.partials)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/partials'));
});
gulp.task('viewsHtml', function() {
gulp.src(paths.html.views)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/views'));
});
gulp.task('styles', ['bower-styles', 'app-styles'], function(){
console.log('starting styles task');
})
gulp.task('bower-styles', function(){
return gulp.src(paths.bower_components_styles)
.pipe(autoprefixer())
.pipe(concat('bower_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('fonts', function() {
return gulp.src(['bower_components/font-awesome/fonts/fontawesome-webfont.*'])
.pipe(gulp.dest('public/dist/fonts/'));
});
gulp.task('app-styles', function(){
return gulp.src(paths.app_styles)
.pipe(autoprefixer())
.pipe(concat('app_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('scripts', ['bower_scripts','app_scripts'], function(){
console.log('starting scripts task');
})
gulp.task('bower_scripts', function(){
console.log('starting bower scripts task');
return gulp.src(paths.bower_components)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('bower_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('app_scripts', function(){
console.log('starting app scripts task');
return gulp.src(paths.app_scripts)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('app_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('default', ['clean', 'html', 'styles', 'fonts', 'scripts'], function(){
console.log('starting default task');
})
This is the output generated for the particular controller
"use strict";angular.module("sbApp").controller("BrandsCtrl",["$scope","$rootScope","$state","CustomStorage","Brands","$uibModalStack",function($scope,$rootScope,$state,CustomStorage,Brands,$uibModalStack){$scope.vm={brand:{title:"",description:""}},$scope.createBrand=function(){return $scope.vm.errorMsg="",$scope.vm.successMsg="",""==$scope.vm.brand.title||null==$scope.vm.brand.title||void 0==$scope.vm.brand.title||$scope.vm.brand.title.length<3||$scope.vm.brand.title.length>30?$scope.vm.errorMsg="The title must be min 3 max 30 letters":""==$scope.vm.brand.description||null==$scope.vm.brand.description||void 0==$scope.vm.brand.description?$scope.vm.errorMsg="Description is required":$scope.vm.brand.description.length<3||$scope.vm.brand.description.length>1e3?$scope.vm.errorMsg="Description must be min 3 max 1000 letters.":($scope.displaySpinner=!0,void Brands.addNew($scope.vm.brand).then(function(response){$scope.vm.brand.title="",$scope.vm.brand.description="",$scope.vm.successMsg=response.data.title+" added successfully."},function(err){$scope.vm.errorMsg=err.data.message?err.data.message:err.data.msg})["finally"](function(){$scope.displaySpinner=!1}))},$scope.disposeModal=function(){$uibModalStack.dismissAll()}}]);
I am getting error for ui.bootstrap modules, angular.min.js:123
Error:
[$injector:unpr]
http://errors.angularjs.org/1.6.4/$injector/unpr?p0=%24uibModalStackProvider%20%3C-%20%24uibModalStack%20%3C-%20InvoiceCtrl%20%3C-%20BrandsCtrl
I have already used gulp-ng-annotate,.pipe(uglify({mangle:false})) in mu gulpfile.js. Please suggest where it is breaking my app for $uibModal and why?
angular version - AngularJS v1.6.4
Node
It seems that you should add dependency on ui.bootstrap module:
angular.module("sbApp", ["ui.bootstrap"])...
It was duplicate files present and concat was actually adding same file twice

ReferenceError: [BABEL] Unknown option.babelrc.presets while parsing file

I am using Babel 6 for es2015 and react I have added the presets property in .babelrc but while running gulp in my project I am getting the following error.
ReferenceError: [BABEL] C:\sunny\ubuntushare\projects\viewpoint_ui\src\javascript\app-nyi.jsx: Unknown option: C:\sunny\ubuntushare\projects\viewpoint_ui\.babelrc.presets while parsing file: C:\sunny\ubuntushare\projects\viewpoint_ui\src\javascript\app-nyi.jsx
at Logger.error (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\logger.js:58:11)
at OptionManager.mergeOptions (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:126:29)
at OptionManager.addConfig (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:107:10)
at OptionManager.findConfigs (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:168:35)
at OptionManager.init (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\options\option-manager.js:229:12)
at File.initOptions (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\index.js:147:75)
at new File (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\file\index.js:137:22)
at Pipeline.transform (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\node_modules\babel-core\lib\transformation\pipeline.js:164:16)
at Babelify._flush (C:\sunny\ubuntushare\projects\viewpoint_ui\node_modules\babelify\index.js:28:24)
at Babelify.<anonymous> (_stream_transform.js:118:12)
My .babelrc file is
{
"presets": ["react","stage-0","es2015"]
}
If I run babel src -d lib command, it works. But if I run gulp build for building the error appears.
The gulpfile is as follows
'use strict';
var _ = require('lodash');
var gulp = require('gulp');
var webserver = require('gulp-webserver');
var browserify = require('browserify');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');
var sass = require('gulp-sass');
var swig = require('gulp-swig');
var rename = require("gulp-rename");
var nodeResolve = require('resolve');
var source = require('vinyl-source-stream');
var del = require('del');
var buffer = require('gulp-buffer');
var concat = require('concat-stream');
var file = require('gulp-file');
var eslint = require('gulp-eslint');
var concatCss = require('gulp-concat-css');
var production = (process.env.NODE_ENV === 'production');
function getNPMPackageIds() {
// read package.json and get dependencies' package ids
var packageManifest = {};
try {
packageManifest = require('./package.json');
} catch (e) {
// does not have a package.json manifest
}
return _.keys(packageManifest.dependencies) || [];
}
gulp.task('lint', function () {
return gulp.src(['./src/javascript/components/**/*.jsx','./src/javascript/actions/*.jsx','./src/javascript/stores/*.jsx','./src/javascript/utilities/*.js'])
// eslint() attaches the lint output to the eslint property
// of the file object so it can be used by other modules.
.pipe(eslint())
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failOnError last.
//.pipe(eslint.failOnError());
});
gulp.task('templates', ['clean'], function () {
gulp.src('./src/htdocs/**/*.html')
.pipe(swig())
.pipe(gulp.dest('./build/'));
});
gulp.task('server', function () {
gulp.src('./build')
.pipe(webserver({
host: '0.0.0.0',
port: 8080,
// fallback: 'index.html',
livereload: true,
proxies: [{
source: '/ui',
target: 'http://localhost:8080/'
}]
}));
});
gulp.task('sass', ['clean'], function () {
var css = gulp.src('./src/sass/**/*.scss')
.pipe(sass().on('error', sass.logError));
if (production) { css = css.pipe(minify()); }
css.pipe(gulp.dest('./build/css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./src/sass/**/*.scss', ['sass']);
});
// main build task
gulp.task('build', ['build-vendor', 'build-app', 'uikit', 'sass', 'templates', 'copyfiles']);
gulp.task('build-vendor', function () {
var b = browserify({
// generate source maps in non-production environment
debug: !production
});
// do the similar thing, but for npm-managed modules.
// resolve path using 'resolve' module
getNPMPackageIds().forEach(function (id) {
b.require(nodeResolve.sync(id), { expose: id });
});
var stream = b.bundle().pipe(source('vendor.js'))
.pipe(buffer())
.pipe(gulp.dest('./build'));
if (production) {
stream = stream.pipe(uglify())
.pipe(gulp.dest('./build'));
}
return stream;
});
function write(name) {
return concat(function (content) {
// create new vinyl file from content and use the basename of the
// filepath in scope as its basename.
var f = file(name, content, { src: true });
// uglify content
if (production) {
f = f.pipe(uglify());
}
// write content to build directory
f.pipe(gulp.dest('./'));
return f;
});
}
gulp.task('build-app', function () {
var files = ['src/javascript/app.jsx', 'src/javascript/app-2f.jsx', 'src/javascript/app-nyi.jsx'];
var b = browserify(files, {
extensions: ['.jsx'],
debug: !production
});
// exclude all NPM modules
getNPMPackageIds().forEach(function (id) {
b.external(id);
});
b.plugin('factor-bundle', {
outputs: [
write('build/app.js'),
write('build/app-2f.js'),
write('build/app-nyi.js')
]
});
var stream = b.transform(babelify, {presets: ["react","stage-0","es2015"]}).bundle()
.pipe(source('common.js'))
.pipe(buffer())
.pipe(gulp.dest('./build/'));
if (production) {
stream = stream.pipe(uglify())
.pipe(gulp.dest('./build'));
}
return stream;
});
gulp.task('clean', function (cb) {
del([
'build/**/*.*'
], cb);
});
gulp.task('uikit', ['clean'], function () {
gulp.src([(production ? './node_modules/': '../') + 'osstools_uikit/assets/css/screen.css', './node_modules/react-widgets/dist/css/react-widgets.css', './node_modules/rc-slider/assets/index.css', './node_modules/react-bootstrap-table/css/react-bootstrap-table-all.css'])
.pipe(concatCss('osstools_uikit.css', {rebaseUrls:false}))
.pipe(gulp.dest('./build/css'));
});
gulp.task('copyfiles', ['clean'], function () {
gulp.src((production ? './node_modules/' : '../') + 'osstools_uikit/assets/images/**/*')
.pipe(gulp.dest('./build/css/images/'));
gulp.src(['./node_modules/react-widgets/dist/fonts/*', (production ? './node_modules/' : '../') + 'osstools_uikit/assets/fonts/**/*'])
.pipe(gulp.dest('./build/fonts/'));
});
gulp.task('watch', ['build-vendor', 'build-app', 'uikit', 'sass', 'templates', 'copyfiles'], function () {
gulp.watch('./src/javascript/components/**/*.jsx', ['build']);
gulp.watch('./src/javascript/stores/*.jsx', ['build']);
gulp.watch('./src/javascript/actions/*.jsx', ['build']);
gulp.watch('./src/javascript/utilities/*.js', ['build']);
gulp.watch('./src/sass/**/*.scss', ['sass']);
gulp.watch('./src/htdocs/**/*.html', ['templates']);
});
gulp.task('default', ['build', 'server', 'watch']);

why browsersync reload multiple times whe a file is changed?

I have a project with angularjs. All the environment is set under nodejs with gulp and bower dependencies.
I have a problem: every time a file is changed, the browser reloads multiple times.
So, I think is problem is related to the browsersync configuration, how I can fix it?
// ////////////////////////////////////////////////
//
// EDIT CONFIG OBJECT BELOW !!!
//
// jsConcatFiles => list of javascript files (in order) to concatenate
// buildFilesFoldersRemove => list of files to remove when running final build
// // //////////////////////////////////////////////
var config = {
jsConcatFilesApi: [
'./js/initapp/*.js',
'./js/services/*.js',
'./js/charts/*.js',
],
jsConcatFilesNavigation: [
'./js/navigation/**/*.js',
],
buildFilesFoldersRemove:[
'./build/scss/',
'./build/js/!(*.min.js)',
'./build/bower.json',
'./build/node_modules/',
'./build/gulpfile.js',
'./build/package.json',
'./build/maps/',
'./build/readme.md'
]
};
// ////////////////////////////////////////////////
// Required taskes
// gulp build
// bulp build:serve
// // /////////////////////////////////////////////
var gulp = require('gulp'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync'),
reload = browserSync.reload,
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
del = require('del');
// ////////////////////////////////////////////////
// Log Errors
// // /////////////////////////////////////////////
function errorlog(err){
console.error(err.message);
this.emit('end');
}
// ////////////////////////////////////////////////
// Scripts Tasks
// ///////////////////////////////////////////////
gulp.task('scriptsApi', function() {
return gulp.src(config.jsConcatFilesApi)
.pipe(sourcemaps.init())
.pipe(concat('temp.js'))
.pipe(uglify())
.on('error', errorlog)
.pipe(rename('d3AcnaDane.min.js'))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./js/min/'))
.pipe(reload({stream:true}));
});
gulp.task('scriptsNavigation', function() {
return gulp.src(config.jsConcatFilesNavigation)
.pipe(sourcemaps.init())
.pipe(concat('temp.js'))
.pipe(uglify())
.on('error', errorlog)
.pipe(rename('navigationAcnaDane.min.js'))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./js/min/'))
.pipe(reload({stream:true}));
});
// ////////////////////////////////////////////////
// Styles Tasks
// ///////////////////////////////////////////////
gulp.task('styles', function() {
gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compressed'}))
.on('error', errorlog)
.pipe(autoprefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('css'))
.pipe(reload({stream:true}));
});
// ////////////////////////////////////////////////
// HTML Tasks
// // /////////////////////////////////////////////
gulp.task('html', function(){
gulp.src('**/*.html')
.pipe(reload({stream:true}));
});
// ////////////////////////////////////////////////
// Browser-Sync Tasks
// // /////////////////////////////////////////////
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// task to run build server for testing final app
gulp.task('build:serve', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// ////////////////////////////////////////////////
// Build Tasks
// // /////////////////////////////////////////////
// clean out all files and folders from build folder
gulp.task('build:cleanfolder', function (cb) {
del([
'./build/**'
], cb);
});
// task to create build directory of all files
gulp.task('build:copy',function(){
return gulp.src('./**/*/')
.pipe(gulp.dest('./build/'));
});
// task to removed unwanted build files
// list all files and directories here that you don't want included
gulp.task('build:remove', function (cb) {
del(config.buildFilesFoldersRemove, cb);
});
gulp.task('build', ['build:copy', 'build:remove']);
// ////////////////////////////////////////////////
// Watch Tasks
// // /////////////////////////////////////////////
gulp.task ('watch', function(){
gulp.watch('scss/**/*.scss', ['styles']);
gulp.watch('js/**/*.js', ['scriptsApi']);
gulp.watch('js/**/*.js', ['scriptsNavigation']);
gulp.watch('**/*.html', ['html']);
});
gulp.task('default', ['scriptsApi','scriptsNavigation', 'styles', 'html', 'browser-sync', 'watch']);

setting proxy or backend URL while doing gulp build:dist

We have some code in Angular JS which is build using gulp (babel).
We have necessity to redirect the api service calls to a different server.
Hence, which development we run gulp server and with that add the api-host server in the proxy argument while running gulp server, as follows:
gulp serve:dist --mock no --proxy http://<host-name>:8090
Now, after development, we build and distribute the same bundle to different host (not the same host where the api services are hosted). Now we are not able to connect to the api server. The command we use to build is
gulp build:dist --mock no
Even if we add the proxy argument here, it doesn't works.
gulp build:dist --mock no --proxy http://<host-name>:8090
We tried customizing the "gulpfile.babel.js" file. but no result.
The following is the "gulpfile.babel.js" used:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');
var _ = require('lodash');
var historyApiFallback = require('connect-history-api-fallback');
var path = require('path');
var args = require('yargs').argv;
var proxyMiddleware = require('http-proxy-middleware');
var merge = require('merge-stream');
// browserSync
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// config & testing
var config = require('./build/build.config.js');
var protractorConfig = require('./build/protractor.config.js');
var karmaConfig = require('./build/karma.config.js');
var KarmaServer = require('karma').Server;
var pkg = require('./package');
/* jshint camelcase:false*/
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);
// util functions
function sortModulesFirst(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a.path);
var bMod = module.test(b.path);
// inject *.module.js first
if (aMod === bMod) {
// either both modules or both non-modules, so just sort normally
if (a.path < b.path) {
return -1;
}
if (a.path > b.path) {
return 1;
}
return 0;
} else {
return (aMod ? -1 : 1);
}
}
// serve app in dev mode or prod mode
function serverOptions(logPrefix) {
var proxy = args.proxy;
var options = {
notify: false,
logPrefix: pkg.name,
server: {
baseDir: ['build', 'client']
}
};
// use a proxy server to serve '/api/**'' and '/auth' routes
if (proxy && args.mock === 'no') {
options.server.middleware = [
proxyMiddleware(['/auth', '/api'], {
target: proxy
}),
historyApiFallback()
];
} else {
// use Angular's $httpBackend as the server
options.server.middleware = [
historyApiFallback()
];
}
if (logPrefix) {
options.logPrefix = pkg.name;
}
return options;
}
// run unit tests and watch files
gulp.task('tdd', function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: false,
action: 'watch',
browsers: ['PhantomJS']
}), cb).start();
});
// run unit tests with travis CI
gulp.task('travis', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true,
browsers: ['PhantomJS']
}), cb).start();
});
// optimize images and put them in the dist folder
gulp.task('images', function() {
return gulp.src(config.images, {
base: config.base
})
.pipe($.imagemin({
progressive: true,
interlaced: true
}))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'images'
}));
});
//generate angular templates using html2js
gulp.task('templates', function() {
return gulp.src(config.tpl)
.pipe($.changed(config.tmp))
.pipe($.html2js({
outputModuleName: 'templates',
base: 'client',
useStrict: true
}))
.pipe($.concat('templates.js'))
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'templates'
}));
});
//generate css files from scss sources
gulp.task('sass', function() {
return gulp.src(config.mainScss)
.pipe($.sass())
.pipe($.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.on('error', $.sass.logError)
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'sass'
}));
});
//generate a minified css files, 2 js file, change theirs name to be unique, and generate sourcemaps
gulp.task('html', function() {
let useminConfig = {
path: '{build,client}',
css: [$.csso(), $.rev()],
vendorJs: [$.uglify({
mangle: false
}), $.rev()],
mainJs: [$.ngAnnotate(), $.uglify({
mangle: false
}), $.rev()]
};
if (args.mock === 'no') {
// Don't include mock vendor js
useminConfig.mockVendorJs = [];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe($.replace('<script src="assets/js/mock-vendor.js"></script>', ''))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
} else {
// Include mock vendor js
useminConfig.mockVendorJs = [$.uglify({
mangle: false
}), $.rev()];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
}
});
// clean up mock vendor js
gulp.task('clean:mock', function(cb) {
if (args.mock === 'no') {
let paths = [path.join(config.dist, 'assets/js/mock-vendor.js')];
del(paths).then(() => {
cb();
});
} else {
cb();
}
});
//copy assets in dist folder
gulp.task('copy:assets', function() {
return gulp.src(config.assets, {
dot: true,
base: config.base
})
//.pipe(gulp.dest(config.dist + '/assets'))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy:assets'
}));
});
//copy assets in dist folder
gulp.task('copy', function() {
return gulp.src([
config.base + '/*',
'!' + config.base + '/*.html',
'!' + config.base + '/src',
'!' + config.base + '/test',
'!' + config.base + '/bower_components'
])
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy'
}));
});
//clean temporary directories
gulp.task('clean', del.bind(null, [config.dist, config.tmp]));
//lint files
gulp.task('jshint', function() {
return gulp.src(config.js)
.pipe(reload({
stream: true,
once: true
}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// babel
gulp.task('transpile', function() {
return gulp.src(config.js)
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015']
}))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(
path.join(config.tmp, 'src')
));
});
// inject js
gulp.task('inject:js', () => {
var injectJs = args.mock === 'no' ?
config.injectJs :
config.injectJs.concat(config.mockJS);
return gulp.src(config.index)
.pipe($.inject(
gulp
.src(injectJs, {
read: false
})
.pipe($.sort(sortModulesFirst)), {
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<script src="' + filepath.replace('/client', 'tmp') + '"></script>'
}))
.pipe(gulp.dest(config.base));
});
/** ===================================
build tasks
======================================*/
//build files for development
gulp.task('build', ['clean'], function(cb) {
runSequence(['sass', 'templates', 'transpile', 'inject:js'], cb);
});
//build files for creating a dist release
gulp.task('build:dist', ['clean'], function(cb) {
//runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images', 'test:unit'], 'html', cb);
runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images'], 'html', 'clean:mock', cb);
});
// For aniden internal usage
// changed app root for labs server
gulp.task('labs:aniden', function() {
let base = `/hpe/mvno_portal/build/v${pkg.version}/`;
let html = gulp.src(config.dist + '/index.html', {
base: config.dist
})
.pipe($.replace('<base href="/">', `<base href="${base}">`))
.pipe(gulp.dest(config.dist));
let css = gulp.src(config.dist + '/**/*.css', {
base: config.dist
})
.pipe($.replace('url(/', `url(${base}`))
.pipe($.replace('url("/', `url("${base}`))
.pipe(gulp.dest(config.dist));
let js = gulp.src(config.dist + '/**/*.js', {
base: config.dist
})
.pipe($.replace('href="/"', `href="${base}"`))
.pipe(gulp.dest(config.dist));
return merge(html, css, js);
});
/** ===================================
tasks supposed to be public
======================================*/
//default task
gulp.task('default', ['serve']); //
//run unit tests and exit
gulp.task('test:unit', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true
}), cb).start();
});
// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
return gulp.src(protractorConfig.config.specs)
.pipe($.protractor.protractor({
configFile: 'build/protractor.config.js'
}))
.on('error', function(e) {
throw e;
});
});
//run the server, watch for file changes and redo tests.
gulp.task('serve:tdd', function(cb) {
runSequence(['serve', 'tdd'], cb);
});
//run the server after having built generated files, and watch for changes
gulp.task('serve', ['build'], function() {
browserSync(serverOptions());
gulp.watch(config.html, reload);
gulp.watch(config.scss, ['sass', reload]);
gulp.watch(config.js, ['jshint', 'transpile']);
gulp.watch(config.tpl, ['templates', reload]);
gulp.watch(config.assets, reload);
});
//run the app packed in the dist folder
gulp.task('serve:dist', ['build:dist'], function() {
browserSync(serverOptions());
});
You can use gulp-ng-config to add constant in you app module.
Or you a JSON as a config file inside your gulp:
//Gulp file
var fs = require('fs');
var settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
....
gulp.task('statics', g.serve({
port: settings.frontend.ports.development,
...
}));
gulp.task('production', g.serve({
port: settings.frontend.ports.production,
root: ['./dist'],
...
}));

Resources