Gulp deleting CSS in html file - html

I have a HTML file with all the scripts and stylesheets that I use in my Web App. When I add a new, custom CSS, and I run gulp, it automatically deletes that new line from the HTML file. My web application is an angular app.
<!-- MATERILIZE CORE CSS-->
<link href="../../common/vendors/Materialize/dist/css/materialize.css" rel="stylesheet"/>
<!-- MAIN STYLE -->
<link href="views/modules/main/min/custom-min.css" rel="stylesheet"/>
<!-- END MAIN STYLE -->
UPDATE 1
this is my gulpfile
( function () {
'use strict';
var //Required
args = require( 'yargs' ).argv,
spawn = require( 'child_process' ).spawn,
cssmin = require( 'gulp-cssnano' ),
concat = require( 'gulp-concat' ),
del = require( 'del' ),
echo = require( 'cli-color' ),
gulp = require( 'gulp' ),
gulpif = require( 'gulp-if' ),
linker = require( 'gulp-linker' ),
ngAnnotate = require( 'gulp-ng-annotate' ),
rename = require( 'gulp-rename' ),
runSequence = require( 'run-sequence' ).use( gulp ),
sass = require( 'gulp-ruby-sass' ),
sourcemaps = require( 'gulp-sourcemaps' ),
uglify = require( 'gulp-uglify' ),
shell = require( 'gulp-shell' ),
node,
// Client FOLDERS
client = {
ROOT: 'web/client/',
SRC_SCSS: 'web/client/source/sass',
EXPORT_CSS: 'web/client/public/css',
SRC_JS: 'web/client/source/js',
EXPORT_JS: 'web/client/public/js'
},
// Dashboard FOLDERS
dashboard = {
ROOT: 'web/dashboard/',
SRC_SCSS: 'web/dashboard/source/sass',
EXPORT_CSS: 'web/dashboard/static/css',
SRC_JS: 'web/dashboard/source/js',
EXPORT_JS: 'web/dashboard/static/js'
},
// Exported FILES
out = {
MINIFIEDCSS: 'app.min.css',
MINIFIEDJS: 'app.min.js'
};
/**
* $ gulp minifyJS --GLOBAL FUNCTION
* description: Concat and minified JS files into *.min.js
*/
gulp.task( 'minifyJS', function () {
return gulp.src( [ args.SRC_JS + '/**/module.js', args.SRC_JS + '/**/*.js' ] )
.pipe( sourcemaps.init() )
.pipe( concat( out.MINIFIEDJS ) )
.pipe( ngAnnotate() )
.pipe( uglify() )
.pipe( sourcemaps.write() )
.pipe( gulp.dest( args.EXPORT_JS ) );
} );
/**
* $ gulp linkJS --GLOBAL FUNCTION
* description: lin all js files to index.html client
*/
gulp.task( 'linkJS', function () {
return gulp.src( args.ROOT + args.FOLDER + 'index.html' )
.pipe( linker( {
scripts: [ ( args.EXPORT_JS + '/' + out.MINIFIEDJS ) ],
startTag: '<!-- APP -->',
endTag: '<!-- END APP -->',
fileTmpl: '<script src="%s"></script>',
appRoot: args.ROOT + args.FOLDER
} ) )
.pipe( gulp.dest( args.ROOT + args.FOLDER ) );
} );
/**
* $ gulp compileSASS --GLOBAL FUNCTION
* description: compile sass file into a CSS file
*/
gulp.task( 'compileSASS', function () {
return sass( args.SRC_SCSS + '/app.scss', {
sourcemap: true
} )
.on( 'error', function ( err ) {
console.error( 'Error!', err.message );
} )
.pipe( gulpif( args.production, sourcemaps.init() ) )
.pipe( gulpif( args.production, cssmin() ) )
.pipe( sourcemaps.write( {
includeContent: false,
sourceRoot: '/' + args.SRC_SCSS
} ) )
.pipe( gulpif( args.production, rename( {
suffix: '.min'
} ) ) )
.pipe( gulp.dest( args.EXPORT_CSS ) );
} );
/**
* $ gulp linkCSS --GLOBAL FUNCTION
* description: link to index.html client all sass files
*/
gulp.task( 'linkCSS', function () {
var isProduction = args.production;
return gulp.src( args.ROOT + args.FOLDER + '/index.html' )
.pipe( linker( {
scripts: isProduction ? [ ( args.EXPORT_CSS + '/' + out.MINIFIEDCSS ) ] : [ ( args.EXPORT_CSS + '/app.css' ) ], //jshint ignore: line
startTag: '<!-- MAIN STYLE -->',
endTag: '<!-- END MAIN STYLE -->',
fileTmpl: '<link href="%s" rel="stylesheet"/>',
appRoot: args.ROOT + args.FOLDER
} ) )
.pipe( gulp.dest( args.ROOT + '/' + args.FOLDER ) );
} );
/**
* $ gulp docs-api --GLOBAL FUNCTION
* description: genereate apidocs
*/
gulp.task( 'docs-api', shell.task( [ 'apidoc -i ./server/handlers -o docs/api/' ] ) );
/**
* $ gulp clean --GLOBAL FUNCTION
* description: clean client side css and js folder
*/
gulp.task( 'clean', function () {
var cleanALL = function () {
del.sync( [ './docs/**' ] );
del.sync( [ args.EXPORT_JS, args.EXPORT_CSS ] );
},
cleanONE = function ( folder ) {
del.sync( [ folder ] );
};
if ( !args.js && !args.css ) {
return cleanALL();
} else {
return args.js ? cleanONE( args.EXPORT_JS ) : cleanONE( args.EXPORT_CSS );
}
} );
/**
* $ gulp server
* description: launch the server. If there's a server already running, kill it.
*/
gulp.task( 'server', function () {
if ( node ) {
node.kill();
}
node = spawn( 'node', [ 'server/server.js' ], {
stdio: 'inherit'
} );
node.on( 'close', function ( code ) {
if ( code === 8 ) {
console.log( echo.redBright.bold( 'Error detected, waiting for changes...' ) );
}
} );
} );
/**
* $ gulp clientJS
* description: Compile all JS files for the Web Client component.
*/
gulp.task( 'clientJS', function ( callback ) {
args = {
js: 'js',
ROOT: client.ROOT,
SRC_JS: client.SRC_JS,
EXPORT_JS: client.EXPORT_JS,
FOLDER: 'public/'
};
runSequence(
'clean',
'minifyJS',
'linkJS',
callback
);
} );
/**
* $ gulp dashJS
* description: Compile all JS files for the Dashboard component.
*/
gulp.task( 'dashJS', function ( callback ) {
args = {
js: 'js',
ROOT: dashboard.ROOT,
SRC_JS: dashboard.SRC_JS,
EXPORT_JS: dashboard.EXPORT_JS,
FOLDER: 'static/'
};
runSequence(
'clean',
'minifyJS',
'linkJS',
callback
);
} );
/**
* $ gulp clientSCSS
* description: Compile all SCSS files for the Web Client component.
*/
gulp.task( 'clientSCSS', function ( callback ) {
args = {
css: 'css',
ROOT: client.ROOT,
SRC_SCSS: client.SRC_SCSS,
EXPORT_CSS: client.EXPORT_CSS,
FOLDER: 'public/'
};
runSequence(
'clean',
'compileSASS',
'linkCSS',
callback
);
} );
/**
* $ gulp dashSCSS
* description: Compile all SCSS files for the Dashboard component.
*/
gulp.task( 'dashSCSS', function ( callback ) {
args = {
css: 'css',
ROOT: dashboard.ROOT,
SRC_SCSS: dashboard.SRC_SCSS,
EXPORT_CSS: dashboard.EXPORT_CSS,
FOLDER: 'static/'
};
runSequence(
'clean',
'compileSASS',
'linkCSS',
callback
);
} );
/**
* $ gulp start
* description: Execute all sub-tasks and start the server,
* including the wathes (to listen for any changes)
*/
gulp.task( 'start', function () {
runSequence(
'clientJS',
'dashJS',
'clientSCSS',
'dashSCSS',
'server',
'watch'
);
} );
/**
* $ gulp watch
* description: watch for any changes and restart server if required
*/
gulp.task( 'watch', function () {
gulp.watch( [ 'server/index.js', './server/**/*.js', './server/**/*.json' ], function () {
runSequence(
'server'
);
} );
// Need to watch for sass changes too? Just add another watch call!
// no more messing around with grunt-concurrent or the like. Gulp is
// async by default.
gulp.watch( client.SRC_SCSS + '/**/*.scss', [ 'clientSCSS' ] );
gulp.watch( client.SRC_JS + '/**/*.js', [ 'clientJS' ] );
gulp.watch( dashboard.SRC_SCSS + '/**/*.scss', [ 'dashSCSS' ] );
gulp.watch( dashboard.SRC_JS + '/**/*.js', [ 'dashJS' ] );
} );
// Clean up if an error goes unhandled.
process.on( 'exit', function () {
if ( node ) {
node.kill();
}
} );
} )();

can you share your gulp code. Probably you might have written some gulp task which will dynamically create your index.html file. Whereever you have written task to add css files make your you have added correct path. May be which ever css files are missing are not in specified path.
gulp.task('inject:css', () => {
return gulp.src(paths.client.mainView)
.pipe(plugins.inject(
gulp.src(`${clientPath}/{app,components}/**/*.css`, {read: true})
.pipe(plugins.sort()),
{
starttag: '<!-- injector:css -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<link rel="stylesheet" href="' + filepath.replace(`/${clientPath}/`, '').replace('/.tmp/', '') + '">'
}))
.pipe(gulp.dest(clientPath));
});
above task will include all css files from app,component
gulp.src(`${clientPath}/{app,components}/**/*.css`, {read: true})
If I add some css files outside those two folders. and add it to index manually. If i run gulp it will be removed
Hoping this will resolve your problem

Related

How to create directory with name given by a prompt question with gulp

I would like to run a gulpfile.js task which asks in prompt the directory name to create it inside the build folder.
Structure
gulfile.js
build/
foo/ <-- directory name given by a question
gulpfile task
gulp.task( 'questions', function( callback ) {
return gulp.src('build')
.pipe( prompt.prompt({
type: 'input',
name: 'dir_name',
message: 'What is directory name ?'
}, function( res ){
//console.log(res.dir_name);
//make directory called res.dir_name in build/
}))
.pipe(gulp.dest('build'));
});
How can I do this ?
I found a solution thanks gulp-prompt package.
This example copy content base folder in build folder.
const prompt = require('gulp-prompt');
var my_dirname, project_build_path ;
gulp.task( 'questions', function( callback ) {
return gulp.src('./base/**/*')
.pipe( prompt.prompt({
type: 'input',
name: 'dir_name',
message: 'What is directory name ?'
}, function( res ){
my_dirname = res.dir_name;
project_build_path = 'build/' + my_dirname;
gulp.src( './base/**/*' ).pipe( gulp.dest( project_build_path ) );
}));
});

gulp add folder in zip archive

gulp.task( 'zip', function () {
return gulp.src( './dist/**' )
.pipe(zip( 'dist.zip' ))
.pipe(gulp.dest( './' ));
});
I have next structure
dist.zip
all-files
How do I make the following structure in the archive?
dist.zip
dist
all-files
Your code is fine except for the gulp.dest which takes a string (or a function):
gulp.task( 'zip', function () {
return gulp.src( './dist/**' )
.pipe(zip( 'dist.zip' ))
// .pipe(gulp.dest( ./ )); your code, note the apostrophes below
.pipe(gulp.dest( './' ));
});

how to change path when including file with gulp-inject

I'm injecting files like this right now:
var gulp = require('gulp');
var inject = require('gulp-inject');
gulp.task('inject_rev', function () {
var target = gulp.src('webapp/dist/somefolder/index.html');
var sources = gulp.src(['webapp/dist/somefolder/*.js',], {read: false});
return target.pipe(inject(sources))
.pipe(gulp.dest('webapp/dist/somefolder/'));
});
But in html file it includes not the path I need, how can I change this path? So for example instead of this:
<script src="/webapp/dist/somefolder/script-1253fe56bd.js"></script>
I could have this:
<script src="/my/own/directory/script-1253fe56bd.js"></script>
I think that you are referring that the dist folder is ok, that will be the public folder, but you need to change only the script-src attribute, to match the respective cdn/static source locations.
try this :
.pipe( $.inject(
gulp.src( ['src/main/webapp/static/dist/**/*.js'], { read : false } ), {
addRootSlash : false,
//ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
console.log('inject script = '+ newPath);
return '<script src="${pageContext.request.contextPath}/' + newPath + '"></script>';
}
} ))
.pipe( $.inject(
gulp.src( ['src/main/webapp/static/dist/**/*.css'], { read : false } ), {
addRootSlash : false,
//ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
console.log('inject style = '+ newPath);
return '<link rel="stylesheet" href="${pageContext.request.contextPath}/' + newPath + '"/>';
}
} ))
change the gulp.src, replace() to match your environment
edit full gulp.js file used in a java application.
In my opinion you should remove the parts that you don't need, and start from scratch, adding one feature after another.
here is my gulpfile
var gulp = require( 'gulp' );
var concat = require( 'gulp-concat' );
// var concatCss = require( 'gulp-concat-css' );
var uglifyCss = require( 'gulp-uglifycss' );
var uglify = require( 'gulp-uglify' );
var minify = require( 'gulp-minify' );
var usemin = require( 'gulp-usemin' );
var imagemin = require( 'gulp-imagemin' );
// var cssnano = require('gulp-cssnano');
var sourcemaps = require( 'gulp-sourcemaps' );
var del = require( 'del' );
var dir = require( 'node-dir' );
var wiredep = require( 'wiredep' ).stream;
var debug = require( 'gulp-debug' );
var runSequence = require( 'run-sequence' );
var bower = require( 'gulp-bower' );
var $ = require( 'gulp-load-plugins' )();
var livereload = require( 'gulp-livereload' );
var injectReload = require( 'gulp-inject-reload' );
var noop = require( 'gulp-util' ).noop;
var plumber = require( 'gulp-plumber' );
var expect = require( 'gulp-expect-file' );
var liveReloadEnabled = false;
var mainBowerFiles = require( 'main-bower-files' );
var bower = require( 'gulp-bower' );
var gutil = require( 'gulp-util' );
var babel = require( 'gulp-babel' );
var browserify = require( 'gulp-browserify' );
var webserver = require( 'gulp-webserver' );
// var minimist = require('minimist');
global.Promise = require( 'bluebird' );
var Q = require( 'q' );
var DEBUG = false;
var SOURCE_MAPS = false;
var PROD = false;
var liveReloadPort = 21232;
var bower_components = 'bower_components';
var paths = {
scripts : ['src/main/javascript/**/*.js*'],// ,'!src/main/webapp/static/dist/**/*'
raw_scripts : ['src/main/webapp/WEB-INF/raw_scripts/**/*.jsp*'],
css : ['src/main/css/**/*.css'],
// bower_dir : 'src/main/webapp/' + bower_components,
bower_dir : bower_components,
// images: 'client/img/**/*'
};
gulp.task( 'main-files', function () {
return gulp.src( mainBowerFiles(), {
base : 'bower_components'
} ).pipe( gulp.dest( 'src/main/webapp/bower_components' ) );
} );
gulp.task( 'scripts-dev', function () {
return gulp.src( paths.scripts )//
.pipe( babel( {
plugins : ['transform-react-jsx', 'transform-runtime'],
presets : ['es2015']
} ) )
.pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( 'src/main/webapp/static/dist/js/' ) )//
} );
gulp.task( 'scripts', function () {
return gulp.src( paths.scripts )//
.pipe( babel( {
plugins : ['transform-react-jsx'],
presets : ['es2015']
} ) )
.pipe( DEBUG ? debug() : noop() )//
.pipe( SOURCE_MAPS || (!PROD) ? sourcemaps.init() : noop() )//
.pipe( uglify( {
mangle : false
} ).on( 'error', gutil.log ) )//
.on( 'error', handleError )//
.pipe( concat( 'bundle.js' ) )//
.pipe( SOURCE_MAPS || (!PROD) ? sourcemaps.write( './' ) : noop() )//
.pipe( gulp.dest( 'src/main/webapp/static/dist/' ) )//
.pipe( liveReloadEnabled ? livereload() : noop() );
} );
gulp.task( 'styles-dev', function () {
return gulp.src( paths.css )//
.pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( 'src/main/webapp/static/dist/css/' ) )//
} );
gulp.task( 'styles', function () {
return gulp.src( paths.css )//
.pipe( DEBUG ? debug() : noop() )//
.pipe( SOURCE_MAPS || (!PROD) ? sourcemaps.init() : noop() )//
.pipe( uglifyCss() ).pipe( concat( 'bundle.css' ) )//
.pipe( SOURCE_MAPS || (!PROD) ? sourcemaps.write( './' ) : noop() )//
.on( 'error', handleError )//
.pipe( gulp.dest( 'src/main/webapp/static/dist/' ) )//
.pipe( liveReloadEnabled ? livereload() : noop() );//
} );
var runUseminForFile = function ( file, base, onEnd ) {
return gulp.src( file, { base : base } )
.pipe( DEBUG ? debug() : noop() )
.pipe( usemin( {
path : base,
//cssnano() seems it does not work
css : [SOURCE_MAPS ? sourcemaps.init( { loadMaps : true } ) : noop(), uglifyCss( { uglyComments : true } ), 'concat', SOURCE_MAPS ? sourcemaps.write( './' ) : noop()],
// uglify() //uglify( { mangle : false } )// uglify( { mangle : false } ).on('error', gutil.log)//minify({ignoreFiles: [ 'min.js']}),
js : [SOURCE_MAPS ? sourcemaps.init( { loadMaps : true } ) : noop(), uglify( { mangle : false } ).on( 'error', gutil.log ), 'concat', SOURCE_MAPS ? sourcemaps.write( './' ) : noop()]
} ) )//
.pipe( gulp.dest( function () {
var remainingFolder = file.substring( file.indexOf( base ) + base.length, file.lastIndexOf( '/' ) + 1 );
if ( DEBUG === true )
console.log( file, remainingFolder, base );
return './tmp/vendor/' + remainingFolder + '/';
} ) )
.on( 'end', onEnd );
};
gulp.task( 'usemin', ['wiredep'], function ( cb ) {
// return
dir.files( './tmp/', function ( err, files ) {
var deferredList = [];
if ( err )
throw err;
for ( var i = 0; i < files.length; i++ ) {
var deferred = Q.defer();
var file = files[i];
if ( file.indexOf( '.jsp' ) === -1 )
continue;
if ( DEBUG === true )
console.log( 'usemin for : ' + './' + file );
runUseminForFile( './' + file, './tmp/', deferred.resolve );
deferredList.push( deferred.promise );
}
Q.all( deferredList ).then( function () {
cb();
} );
} );
} );
gulp.task( 'debug', function ( cb ) {
DEBUG = true;
cb();
} );
gulp.task( 'sourcemaps', function ( cb ) {
SOURCE_MAPS = true;
cb();
} );
gulp.task( 'clean', function () {
return del.sync( ['tmp/', 'src/main/webapp/bower_components', 'src/main/webapp/static/dist',
'src/main/webapp/static/vendor'], function ( err, paths ) {
if ( DEBUG === true )
console.log( 'Deleted files/folders:\n', paths.join( '\n' ) );
} );
} );
gulp.task( 'copy-bower-fonts', function () {
return gulp.src( paths.bower_dir + '/**/*.{ttf,woff,eof,svg}', {
base : paths.bower_dir
} ).pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( './src/main/webapp/static/vendor/font/' ) );
} );
gulp.task( 'copy-bower-images', function () {
return gulp.src( paths.bower_dir + '/**/*.{png,jpg,svg}', {
base : paths.bower_dir
} ).pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( './src/main/webapp/static/images/' ) );
} );
gulp.task( 'min-and-replace', ['usemin'], function ( cb ) {
// the base option sets the relative root for the set of files,
// preserving the folder structure
gulp.src( ['tmp/vendor/**/*.jsp*'], {
base : './tmp/vendor/'
} )//
.pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( 'src/main/webapp/WEB-INF/views/scripts/' ) ).on( 'end', function () {
gulp.src( ['tmp/vendor/**/*.js', 'tmp/vendor/**/*.css'], {
base : './tmp/vendor/${pageContext.request.contextPath}/static/'
} ).pipe( DEBUG ? debug() : noop() )//
.pipe( gulp.dest( 'src/main/webapp/static/' ) ).on( 'end', function () {
del.sync( ['tmp/'], function ( err, paths ) {
if ( DEBUG === true )
console.log( 'Deleted files/folders:\n', paths.join( '\n' ) );
} );
cb();
} );
} );
} );
gulp.task( 'wiredep', ['sync-install-scripts-styles'], function () {
return gulp.src( paths.raw_scripts )//
.pipe( DEBUG ? debug() : noop() )//
.pipe( wiredep( {
directory : paths.bower_dir,//
dependencies : true, // default: true
devDependencies : true, // default: false
// ignorePath : '../../',
fileTypes : {
jsp : {
replace : {
js : function ( filePath ) {
var newPath = filePath.substring( filePath.indexOf( bower_components ) + bower_components.length );
if ( DEBUG === true )
console.log( 'bower script = ' + newPath );
return '<script src="../' + paths.bower_dir + newPath + '"></script>';
},
css : function ( filePath ) {
var newPath = filePath.substring( filePath.indexOf( bower_components ) + bower_components.length );
if ( DEBUG === true )
console.log( 'bower style = ' + newPath );
return '<link rel="stylesheet" href="../' + paths.bower_dir + newPath + '"/>';
}
}
}
}
} ) )//
.pipe( $.inject( gulp.src( ['src/main/webapp/static/dist/**/*.js'], {
read : false
} ), {
addRootSlash : false,
// ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
if ( DEBUG === true )
console.log( 'inject script = ' + newPath );
return '<script src="${pageContext.request.contextPath}/' + newPath + '"></script>';
}
} ) )//
.pipe( $.inject( gulp.src( ['src/main/webapp/static/dist/**/*.css'], {
read : false
} ), {
addRootSlash : false,
// ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
if ( DEBUG === true )
console.log( 'inject style = ' + newPath );
return '<link rel="stylesheet" href="${pageContext.request.contextPath}/' + newPath + '"/>';
}
} ) )//
.pipe( gulp.dest( './tmp/' ) );
} );
gulp.task( 'sync-install-scripts-styles', function ( cb ) {
runSequence( 'install', ['scripts', 'styles'], cb );
} );
gulp.task( 'wiredep-live', function ( cb ) {
return gulp.src( paths.raw_scripts )//
.pipe( DEBUG ? debug() : noop() )//
.pipe( wiredep( {
directory : paths.bower_dir,//
dependencies : true, // default: true
devDependencies : true, // default: false
// ignorePath : '../../../../',
fileTypes : {
jsp : {
replace : {
js : function ( filePath ) {
var newPath = filePath.substring( filePath.indexOf( bower_components ) );
if ( DEBUG === true )
console.log( 'bower script = ' + newPath );
return '<script src="${pageContext.request.contextPath}/' + newPath + '"></script>';
},
css : function ( filePath ) {
var newPath = filePath.substring( filePath.indexOf( bower_components ) );
if ( DEBUG === true )
console.log( 'bower style = ' + newPath );
return '<link rel="stylesheet" href="${pageContext.request.contextPath}/' + newPath + '"/>';
}
}
}
}
} ) )//
.pipe( $.inject( gulp.src( ['src/main/webapp/static/dist/**/*.js'], {
read : false
} ), {
addRootSlash : false,
// ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
if ( DEBUG === true )
console.log( 'inject script = ' + newPath );
return '<script src="${pageContext.request.contextPath}/' + newPath + '"></script>';
}
} ) )//
.pipe( $.inject( gulp.src( ['src/main/webapp/static/dist/**/*.css'], {
read : false
} ), {
addRootSlash : false,
// ignorePath : 'src/main/webapp',
transform : function ( filePath, file, i, length ) {
var newPath = filePath.replace( 'src/main/webapp/', '' );
if ( DEBUG === true )
console.log( 'inject style = ' + newPath );
return '<link rel="stylesheet" href="${pageContext.request.contextPath}/' + newPath + '"/>';
}
} ) )//
.pipe( liveReloadEnabled ? injectReload( {
port : liveReloadPort,
host : 'http://localhost'
} ) : noop() ).pipe( gulp.dest( './src/main/webapp/WEB-INF/views/scripts/' ) );
} );
gulp.task( 'wiredep-full-live', function ( cb ) {
runSequence( 'sync-install-scripts-styles', 'wiredep-live', cb );
} );
// Copy all static images
// gulp.task('images', ['clean'], function() {
// return gulp.src(paths.images)
// // Pass in options to the task
// .pipe(imagemin({optimizationLevel: 5}))
// .pipe(gulp.dest('build/img'));
// });
// Rerun the task when a file changes
gulp.task( 'watch', function () {
liveReloadEnabled = true;
livereload.listen( liveReloadPort );
runSequence( 'wiredep-full-live' );
gulp.watch( paths.scripts, ['scripts'] );
gulp.watch( paths.css, ['styles'] );
gulp.watch( paths.raw_scripts, ['wiredep-live'] );
gulp.watch( ['bower.json'], ['wiredep-full-live'] );
} );
function handleError( error ) {
// If you want details of the error in the console
console.log( error.toString() );
if ( liveReloadEnabled === true )
this.emit( 'end' );
else
fail( error );
}
gulp.task( 'live-reload', function () {
return gulp.src( './src/main/webapp/WEB-INF/views/scripts/**/*.jsp*' ).pipe( injectReload( {
host : 'http://localhost'
} ) ).pipe( gulp.dest( './src/main/webapp/WEB-INF/views/scripts/' ) );
} );
gulp.task( 'del-components', function () {
del.sync( 'target/**/bower_components', function ( err, paths ) {
if ( DEBUG === true )
console.log( 'Deleted files/folders:\n', paths.join( '\n' ) );
} );
} );
gulp.task( 'dev', ['clean', 'sourcemaps', 'wiredep-full-live'] );
gulp.task( 'stage', function ( cb ) {
runSequence( 'clean', 'wiredep-full-live', cb );
} );
gulp.task( 'prod', function ( cb ) {
PROD = true;
runSequence( 'clean', 'min-and-replace', cb );// , 'del-components'
} );
gulp.task( 'install', function ( cb ) {
runSequence( 'bower-install', 'main-files', cb );
} );
gulp.task( 'js', function () {
return gulp.src( "src/main/javascript/app.js" )
.pipe( browserify( {
transform : 'reactify',
debug : true
} ) )
.on( 'error', function ( err ) {
console.error( 'Error!', err.message );
} )
.pipe( concat( 'bundle.js' ) )//
.pipe( gulp.dest( "src/main/webapp/static/dist/" ) );
} );
gulp.task( 'ss', function ( cb ) {
runSequence( 'clean', 'js', cb );
} );
// gulp.task('webserver', function() {
// gulp.src( app + '/')
// .pipe(webserver({
// livereload: true,
// open: true
// }));
// });
gulp.task( 'default', ['watch', 'html', 'js', 'css', 'webserver'] );
//gulp.task( 'bower-install', function( cb ) {
// bower.commands.install( [], {
// save : true
// }, {} ).on( 'end', function( installed ) {
// cb( ); // notify gulp that this task is finished
// } );
//} );
gulp.task( 'bower-install', function ( cb ) {
return bower();
} );
// The default task (called when you run `gulp` from cli)
gulp.task( 'default', ['clean', 'dev'] ); // 'images' // 'watch'
you can use ignorePath attribute
gulp.src(paths.html)
.pipe(inject(gulp.src('_YOUR_PATH_', {read: false}), {ignorePath: '/webapp', addRootSlash: false}))

Using Browserify with a revision manifest in Gulp, getting "Error: write after end"

I'm trying to compile a React app, append a hash to the output filename and produce a revision manifest, so that I can tell the browser to cache it forever. The problem is that the dozen or so tools involved don't all work together perfectly, at least as far as I can figure out by trying to assimilate all of their readmes and juggle .pipe calls.
Gulpfile: gist
Gulp task:
gulp.task( 'compile:js', function() {
var browserifyTransform = transform( function( filename ) {
return browserify( filename )
.transform( reactify )
.bundle();
});
return gulp.src( 'src/index.js' )
.pipe( browserifyTransform )
.pipe( sourcemaps.init({ loadMaps: true }))
.pipe( uglify() )
.pipe( rev() )
.pipe( gulp.dest( 'static/dist' ));
});
update Simplified version, same error:
gulp.task( 'compile:js', function() {
var browserifyTransform = transform( function( filename ) {
return browserify( filename )
.transform( reactify )
.bundle();
});
return gulp.src( 'src/index.js' )
.pipe( browserifyTransform )
.pipe( gulp.dest( 'static/dist' ));
});
Error stack:
[15:55:04] Using gulpfile ~/Projects/pixsplodr/gulpfile.js
[15:55:04] Starting 'compile:js'...
Error: write after end
at writeAfterEnd (/home/dan/Projects/pixsplodr/node_modules/browserify/node_modules/readable-stream/lib/_stream_writable.js:161:12)
at Labeled.Writable.write (/home/dan/Projects/pixsplodr/node_modules/browserify/node_modules/readable-stream/lib/_stream_writable.js:208:5)
at write (_stream_readable.js:601:24)
at flow (_stream_readable.js:610:7)
at _stream_readable.js:578:7
at process._tickCallback (node.js:419:13)
There are a few open bugs that result in this error (example: github.com/hughsk/vinyl-transform/issues/1). The problem with them is that when the original src stream ends, it ends the writable stream, which is still being used. Hence the error.
Try this instead.
gulp.task( 'compile:js', function() {
var browserifyTransform = transform( function( filename ) {
return browserify( filename )
.transform( reactify )
.bundle();
});
gulp.src( 'src/index.js' )
.pipe( browserifyTransform )
.pipe( sourcemaps.init({ loadMaps: true }))
.pipe( uglify() )
.pipe( rev() )
.pipe( gulp.dest( 'static/dist' ));
return gulp.src( '');
});
By returning a seperate gulp.src, gulp is forced to wait until the initial command is finished in order to return the new src.
I resolve this issue using gulp-streamify package.
I had to rewrite my task as follow:
gulp = require('gulp');
rev = require('gulp-rev'); // add hash to filename
rimraf = require('gulp-rimraf'); // delete folder
gulpsync = require('gulp-sync')(gulp); // sync gulp task
babel = require('gulp-babel'); // es6 transpiler
browserify = require('browserify');
source = require('vinyl-source-stream');
streamify = require('gulp-streamify');
gulp.task('compile-es6', function(){
var stream = browserify('app/assets/javascript/application.js')
.transform("babelify", {presets: ["es2015"]})
.bundle();
return stream.pipe(source('bundle.js'))
.pipe(streamify(rev()))
.pipe(gulp.dest('public/javascripts'))
.pipe(rev.manifest('./rev-manifest.json',{merge:true}))
.pipe(gulp.dest(''));
});
Well, I have solution that satisfies my requirements, but it isn't perfect.
Let Browserify start the stream from a file name, instead of using gulp.src
Use vinyl-source-stream to transform Browserify's Node stream to a Gulp stream, before passing the data on to other gulp plugins
I am also using gulp-rev to append a hash to generated filenames, and to create a manifest that maps them to their original filename.
I was having trouble with source maps earlier too, but I have found that using Browserify transforms and settings seems to work better than using Gulp plugins on Browserify's output. That might be entirely due to user error, but I have been seeing so many conflicting Browserify / Gulp examples and minimal examples that I was unable to extend in an intuitive way, that I am just glad to have a working build with all of the features that I wanted.
var gulp = require( 'gulp' );
var gutil = require( 'gulp-util' );
var watchify = require( 'watchify' );
var browserify = require( 'browserify' );
var source = require( 'vinyl-source-stream' );
var buffer = require( 'vinyl-buffer' );
var sass = require( 'gulp-sass' );
var _ = require( 'lodash' );
var rev = require( 'gulp-rev' );
// Dev build
gulp.task( 'watch', [ 'sass' ], function() {
gulp.watch( 'node_modules/quiz/style/**/*.scss', [ 'sass' ]);
builder( './src/app/index.js', true ).bundle( './dist/static', 'quiz-app.min.js' );
});
// Production build
gulp.task( 'build', [ 'sass' ], function() {
builder( './src/app/index.js', false ).bundle( './dist/static', 'quiz-app.min.js' );
});
// snip //
function builder( entry, isDev ) {
var bundler;
if( isDev ) {
bundler = watchify( browserify(
'./src/app/index.js',
_.extend( watchify.args, { debug: true })
));
} else {
bundler = browserify(
'./src/app/index.js'
);
}
bundler.transform( 'reactify' );
bundler.transform( 'es6ify' );
bundler.transform({ global: true }, 'uglifyify' );
bundler.on( 'log', gutil.log ); // Help bundler log to the terminal
function bundle( dest, filename ) {
return bundler.bundle()
.on( 'error', gutil.log.bind( gutil, 'Browserify error' )) // Log errors during build
.pipe( source( filename ))
.pipe( buffer() )
.pipe( rev() )
.pipe( gulp.dest( dest ))
.pipe( rev.manifest() )
.pipe( gulp.dest( dest ));
}
return { bundle: bundle };
}
I also tried just using the tools from NPM scripts, but I was unable to find a good way to do incremental builds while watching a set of files.

Gulp livereload on imagemin task?

I have the following gulp which processes my sass, js and images. I've also got livereload on all tasks. It's working perfectly on all tasks but the image task.
If I place or update an image in the source directory it doesn't reload but it does for all other tasks.
Can someone please point out what I'm doing wrong?
// Required Plugins
var gulp = require('gulp'),
connect = require('gulp-connect'),
livereload = require("gulp-livereload"),
gutil = require('gulp-util'),
notify = require('gulp-notify'),
scss = require('gulp-ruby-sass'),
sass = require('gulp-sass'),
autoprefix = require('gulp-autoprefixer'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
concat = require('gulp-concat'),
changed = require('gulp-changed'),
clean = require('gulp-clean'),
rename = require('gulp-rename'),
minifycss = require('gulp-minify-css'),
newer = require('gulp-newer'),
exec = require('child_process').exec,
sys = require('sys');
// Config
var paths = {
scss: 'site/source/scss/**/*.scss',
js: 'site/source/js/**/*.js',
images: ['site/source/images/**/*.png', 'site/source/images/**/*.gif', 'site/source/images/**/*.jpg', 'site/source/images/**/*.svg'],
html: 'site/**/*.html',
root: 'site/',
},
dests = {
css: 'site/assets/css/',
js: 'site/assets/js/',
images: 'site/assets/images/',
},
options = {
autoprefix: 'last 10 version',
imagemin: { optimizationLevel: 3, progressive: true, interlaced: true },
jshint: '',
jshint_reporter: 'default',
scss: { style: 'compressed', compass: true, require: ['compass', 'susy', 'breakpoint'] },
uglify: { mangle: false },
clean: { read: false }
};
// Clean Task
gulp.task('clean', function() {
return gulp.src([
dests.css, dests.js, dests.images
], options.clean )
.pipe( clean() );
});
// SASS
gulp.task('styles', function () {
return gulp.src( paths.scss )
.pipe( scss( options.scss ).on( 'error', gutil.log ) )
.pipe( autoprefix( options.autoprefix ) )
.pipe( gulp.dest( dests.css ) )
.pipe( connect.reload() )
.pipe( notify( { message: 'CSS task complete.' } ) );
});
// Scripts
gulp.task('scripts', function () {
return gulp.src( paths.js )
.pipe( jshint( options.jshint ) )
.pipe( jshint.reporter( options.jshint_reporter ) )
.pipe( gulp.dest( dests.js ) )
.pipe( uglify( options.uglify ) )
.pipe( concat( 'all.min.js' ) )
.pipe( gulp.dest( dests.js ) )
.pipe( connect.reload() )
.pipe( notify( { message: 'Scripts task complete.' } ) );
});
// Images
gulp.task('images', function() {
return gulp.src( paths.images )
.pipe( imagemin( options.imagemin ) )
.pipe( newer( dests.images ) )
.pipe( gulp.dest( dests.images ) )
.pipe( connect.reload() )
.pipe( notify( { message: 'Images task complete.' } ) );
});
// HTML
gulp.task( 'html', function () {
return gulp.src( paths.html )
.pipe( connect.reload() );
});
// Gulp Connect Server
gulp.task('connect', function() {
connect.server({
root: paths.root,
livereload: true
});
});
// Watch
gulp.task('watch', function () {
gulp.watch( paths.scss, ['styles'] );
gulp.watch( paths.js, ['scripts'] );
gulp.watch( paths.images, ['images'] );
gulp.watch( paths.html, ['html'] );
});
// Default task
// Note we make sure the clean task will finish before running the other tasks
gulp.task('default', ['clean'], function() {
gulp.start( 'styles', 'scripts', 'images', 'connect', 'watch' );
});
The only thing I can notice looking at https://www.npmjs.org/package/gulp-newer
It seems you might have this piece of code the wrong way around:
.pipe( imagemin( options.imagemin ) )
.pipe( newer( dests.images ) )
It should be instead:
.pipe( newer( dests.images ) )
.pipe( imagemin( options.imagemin ) )
Maybe try swapping them around to see if it makes a difference?
Also you can try without the newer stream.