how to change path when including file with gulp-inject - gulp

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}))

Related

Autodesk Forge - Browser labels problems

I have a problem with Forge browser using AggregatedView.
If I load 3 models in the viewer, in the browser appears label "Model" 3 times, instead of revit file name ("1.rvt", "2.rvt" e "3.rvt"), as reported in the attached imageforge browser.
Is it possible to change the behavior (using some options)?
I've tried to use "accessControlProperties" option (https://forge.autodesk.com/en/docs/viewer/v2/reference/javascript/document/#load-documentid-onsuccesscallback-onerrorcallback-accesscontrolproperties) but nothing changes.
TIA
Alder
function fetchForgeToken( callback ) {
callback( "eyJhbGciOiJSUzI1NiIsImtpZCI6IlU3c0dGRldUTzlBekNhSzBqZURRM2dQZXBURVdWN2VhIn0.eyJzY29wZSI6WyJkYXRhOnJlYWQiLCJkYXRhOmNyZWF0ZSIsImRhdGE6d3JpdGUiLCJ2aWV3YWJsZXM6cmVhZCJdLCJjbGllbnRfaWQiOiJpSGVHMlRrbW9ucmF6TjUyS1JoRUdHWnZFTVU3RWg3dCIsImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9hand0ZXhwNjAiLCJqdGkiOiJpVEVVZTdYdVRqam9MVzFnNzQyYWNrREtkd244Q3ZLRHZLcXI1NzBrVkk2ZUR6dzRlNDc3N1BkeFNhelRCWWo3IiwiZXhwIjoxNjI3MzAzNjQ0fQ.VNZZHhuo4fGLsy-StB_YLkEtFNphPuuTDCJt-NtAvzGOD8_dsRjj6szBm9-rXNqKIBUVeg3DkYHG3jfSFQeAN_ie76H2_fVs-zmHMelNi6jZBvyM6DGoE62068TvKpEK9_8po__YstQ1JygEuUyiqivXE0-RqYEjd15wNrb1PUqVJTA-Ug4lEEIGmFNyhQsW861MwcRklkcHzhC9gDijQKqcDAqC_udueWZ5Bh48SPtNNJe4bXFwWcWqEipom-apyArd1nLw9-fpmNd-qPgSQJwNo_0sk-wEIn1Zl6Uq8k67f1bBXBrg7XfUAS2-_M_YOTrHZFl6QVEQ-fvKr4PR9g", "2000" );
}
function launchViewer( models ) {
if( !models || models.length <= 0 )
return console.error( 'Empty model input' );
const options = {
env: 'AutodeskProduction',
getAccessToken: fetchForgeToken
};
const options3d = {
viewerConfig: {
disableBimWalkInfoIcon: true
}
};
function loadManifest( documentId, documentName ) {
return new Promise(( resolve, reject ) => {
const onDocumentLoadSuccess = ( doc ) => {
//doc.downloadAecModelData();
doc.downloadAecModelData(() => resolve(doc));
};
console.log("doc.id = " + documentId);
//var accessControlProperties = {name: documentName};
var accessControlProperties = {modelNameOverride: documentName};
//https://forge.autodesk.com/en/docs/viewer/v2/reference/javascript/document/#load-documentid-onsuccesscallback-onerrorcallback-accesscontrolproperties
//oppure
//https://forge.autodesk.com/blog/customizing-model-browser-custom-label-behavior-styling-and-data-sources
Autodesk.Viewing.Document.load( documentId, onDocumentLoadSuccess, reject, accessControlProperties );
});
}
Autodesk.Viewing.Initializer( options, function() {
//get the viewer div
const viewerDiv = document.getElementById( 'viewer' );
//initialize the viewer object
const view = new Autodesk.Viewing.AggregatedView();
view.init( viewerDiv, options3d );
const viewer = view.viewer;
const tasks = [];
models.forEach( md => tasks.push( loadManifest( md.urn, md.name ) ) );
Promise.all(tasks)
.then( docs => Promise.resolve( docs.map( doc => {
const bubbles = doc.getRoot().search({type:'geometry', role: '3d'});
const bubble = bubbles[0];
if( !bubble ) return null;
return bubble;
})))
.then( bubbles => view.setNodes( bubbles ) );
});
}
const models = [
{ name: '1.rvt', urn: 'urn:dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLm5kLXcyZUNSU3ktdHhHTmZ6OWo4bFE/dmVyc2lvbj0x' },
{ name: '2.rvt', urn: 'urn:dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLkxHVDFOSW1nUlgtZnN0cnhMZUU5aUE/dmVyc2lvbj0x' },
{ name: '3.rvt', urn: 'urn:dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLjhTbE1zOGNWUllTenV1TGR6SXJiWHc/dmVyc2lvbj0x' }
];
launchViewer( models.concat() );
To assign modelNameOverride, we need to take advantage of getCustomLoadOptions. See below code snippet for example:
const options3d = {
viewerConfig: {
disableBimWalkInfoIcon: true,
},
getCustomLoadOptions: (bubble) => {
const modelName = bubble.getDocument().getRoot().search({ role: "viewable" })[0].data.name;
console.log(modelName);
let loadOptions = { modelNameOverride: modelName };
return loadOptions;
}
};
view.init( viewerDiv, options3d );

Gulp deleting CSS in html file

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

Change stream file names on the go in gulp-watch task

Even though it is not that necessary I want to have my dev-environment as clean as possible and therefore automatically remove deleted files from my build directory.
Since I'm using TypeScript I want to have the compiled and static files in one directory on the fly. I'm achieving this with watching static files and copying them to a build folder (I probably should rename that in the future).
Deleted files should then also be removed from the build directory. I tried this and almost succeeded. The only thing I'm trying to find out is how to change a stream file name from app/tmp.html to build/app/tmp.html.
This is my watch-task so far:
let gulp = require( 'gulp' );
let watch = require( 'gulp-watch' );
let filter = require( 'gulp-filter' );
let clean = require( 'gulp-clean' );
gulp.task( 'watch', function() {
let deletedFilter = filter( file => {
return file.event !== 'unlink' && file.event !== 'deleted';
}, { restore: true } );
let newFilter = filter( file => {
return file.event !== 'add';
} );
watch( './app/**/*.{html,css,js,map,svg,png,jpg}' )
.pipe( deletedFilter )
.pipe( gulp.dest( './build/app/' ) )
.pipe( newFilter )
.pipe( deletedFilter.restore ) // this line here
.pipe( clean() ); // and that line there still make
// some trouble
} );
Thank you so much for any help!
Okay, I was taking a little break and dug into a little deeper. Looking at gulp-debug I came up with a solution, using the following, additional node modules to gulp and gulp-watch:
gulp-filter to filter out deleted files in the first place
through2 to go through all filtered (deleted) files
path to get the relative path
gulp-clean to actually remove the files from the build directory
All together it looks something like this (as of writing this answer, I'm using NodeJS 5.10.1):
'use strict';
let staticFilePattern = `./app/**/*.{html,css,js,map,svg,png,jpg}`;
let buildDirectory = 'build';
let gulp = require( 'gulp' );
let watch = require( 'gulp-watch' );
let filter = require( 'gulp-filter' );
let clean = require( 'gulp-clean' );
let through = require( 'through2' );
let path = require( 'path' );
let changeToBuildDirectory = function() {
return through.obj( function( file, enc, cb ) {
file.path = process.cwd() + `/${buildDirectory}/` + path.relative( process.cwd(), file.path );
cb( null, file );
});
};
gulp.task( 'watch', function() {
let deletedFilter = filter( file => {
return file.event !== 'unlink' && file.event !== 'deleted';
}, { restore: true } );
let newFilter = filter( file => {
return file.event !== 'add';
} );
watch( staticFilePattern )
.pipe( deletedFilter )
.pipe( gulp.dest( `./${buildDirectory}/app/` ) )
.pipe( newFilter )
.pipe( debug( { title: 'Foo' } ) )
.pipe( deletedFilter.restore )
.pipe( changeToBuildDirectory() )
.pipe( clean() );
} );
I don't find it very clean, since I'm just modifying the path on the file object, but it works, so I'm pleased. If you got a more clean solution, you are welcome to post another answer or leave it in the comments
I hope it is useful to some extend.
Cheers!

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.