Combine two gulp tasks into one JS file - javascript

I have the following two tasks:
gulp.task('compress', () => {
return gulp.src('app/static/angular/**/*.js')
.pipe(concat('build.js'))
.pipe(gulp.dest('./app/static'));
});
gulp.task('templates', () => {
return gulp.src('app/static/angular/**/*.html')
.pipe(htmlmin())
.pipe(angularTemplateCache('templates.js', {
module: 'myApp',
root: '/static/angular'
}))
.pipe(gulp.dest('./app/static'))
});
And it works fine, but I want them both concatenated into build.js -- how can I combine these two?

In the end I used merge-stream to merge the two streams into one output file:
var gulp = require('gulp');
var concat = require('gulp-concat');
var htmlmin = require('gulp-htmlmin');
var angularTemplateCache = require('gulp-angular-templatecache');
var merge = require('merge-stream');
gulp.task('build', () => {
var code = gulp.src('app/static/angular/**/*.js');
var templates = gulp.src('app/static/angular/**/*.html')
.pipe(htmlmin())
.pipe(angularTemplateCache({
module: 'myApp',
root: '/static/angular'
}));
return merge(code, templates)
.pipe(concat('build.js'))
.pipe(gulp.dest('./app/static'));
});
gulp.task('default', ['build']);

I assume the above task mentioned is in separate file say compress.js inside tasks folder
In gulpfile.js you can use below code :
//Include require-dir to include files available in tasks directory
var requireDir = require('require-dir');
// And Take the tasks directory
requireDir('./tasks');
Then you can create a build task as below in gulpfile.js:
gulp.task('build', ['compress', 'templates']);

Related

Gulp browserify order/sort files

I've got a Gulp task using browserify and watchify. As you can see I've got four files. modules.js uses the class from overlay-model.js.
But browserify doens't keep the order I'm passing. Instead of that browserify puts the files in alphabetical order so it first uses modules.js.
I'll tried looking for a solution gulp sort doens't seem to work and I can't find a browserify-ish solution.
Anyone knows something about this?
var gulp = require('gulp');
var gutil = require('gulp-util');
var c = gutil.colors;
var sort = require('gulp-sort');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
function compile(watch) {
var bundler = watchify(browserify([
'./assets/js/overlay-model.js',
'./assets/js/slider.js',
'./assets/js/words.js',
'./assets/js/modules.js'
], {
debug: true
})
.transform(babel.configure({
presets: ['es2015']
})));
function rebundle() {
bundler.bundle()
.on('error', function(err) { console.error(err); this.emit('end'); })
.pipe(source('build.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public'));
}
if (watch) {
gutil.log(`${c.cyan('scripts')}: watching`);
bundler.on('update', function() {
gutil.log(`${c.cyan('scripts')}: processing`);
rebundle();
});
}
rebundle();
}
function watch() {
return compile(true);
};
gulp.task('build', function() { return compile(); });
gulp.task('watch', function() { return watch(); });
gulp.task('scripts', ['watch']);
I think typically you'll have just one entry point (modules.js in your case) that'll use require(...) to load other modules in order you want.
// modules.js
require('./overlay-model');
require('./slider');
require('./modules');
Then use browserify like:
browserify('./assets/js/modules.js', ...);

Gulp Bundle + Browserify on multiple files

So I have asimple gulp task function which currently converts my main.jsx to a main.js file:
gulp.task("bundle", function () {
return browserify({
entries: "./app/main.jsx",
debug: true
}).transform(reactify)
.bundle()
.pipe(source("main.js"))
.pipe(gulp.dest("app/dist"))
});
I was wondering if it would be possible to put multiple bundles in this gulp.task?
My ideal outcome would be being able to do:
main.jsx to main.js
otherPage.jsx to otherPage.js
otherPage2.jsx to otherPage2.js
All in one gulp task.
I have searched onliine but cannot seem to find anything relevant, any help or advice is appreciated, thank you in advance.
If you want to create a bundle for each file you need to loop over the respective files, create a stream for each file and then merge the streams afterwards (using merge-stream):
var merge = require('merge-stream');
gulp.task("bundle", function () {
var files = [ "main", "otherPage", "otherPage2" ];
return merge(files.map(function(file) {
return browserify({
entries: "./app/" + file + ".jsx",
debug: true
}).transform(reactify)
.bundle()
.pipe(source(file + ".js"))
.pipe(gulp.dest("app/dist"))
}));
});
The above requires that you maintain a list of files manually as an array. It's also possible to write a task that bundles all .jsx files in the app directory without having to maintain an explicit array of the files. You just need the glob package to determine the array of files for you:
var merge = require('merge-stream');
var glob = require('glob');
var path = require('path');
gulp.task("bundle", function () {
var files = glob.sync('./app/*.jsx');
return merge(files.map(function(file) {
return browserify({
entries: file,
debug: true
}).transform(reactify)
.bundle()
.pipe(source(path.basename(file, '.jsx') + ".js"))
.pipe(gulp.dest("app/dist"))
}));
});

How to process *.js and *.min.js bower files in gulp

In my gulp file to inject bower components I have this bad style code duplication. But I do not have any ideas how to get rid of it.
Generally speaking we cannot say just bower_components/**/*.js because we don't want to import all files, plus for production we want to import just .min files. Again. I cannot guaranty that every package I use have .js and .min.js files. So just *.js and *.min.js may not work.
gulp.task('inject', () => {
let sources = gulp.src([
// jquery
'public/bower_components/jquery/dist/jquery.js',
// bootstrap
'public/bower_components/bootstrap/dist/js/bootstrap.js',
'public/bower_components/bootstrap/dist/css/bootstrap.css',
// angular
'public/bower_components/angular/angular.js',
'public/bower_components/angular/angular-csp.css',
// angular route
'public/bower_components/angular-route/angular-route.js',
],{read: false});
let min_sources = gulp.src([
// jquery
'public/bower_components/jquery/dist/jquery.min.js',
// bootstrap
'public/bower_components/bootstrap/dist/js/bootstrap.min.js',
'public/bower_components/bootstrap/dist/css/bootstrap.min.css',
// angular
'public/bower_components/angular/angular.min.js',
'public/bower_components/angular/angular-csp.css',
// angular route
'public/bower_components/angular-route/angular-route.min.js',
],{read: false});
return gulp.src('public/build/index.html')
.pipe(gulpif(!argv.production, inject(sources, {relative: true})))
.pipe(gulpif(argv.production, inject(min_sources, {relative: true})))
.pipe(gulp.dest('public/build/'));
});
But this code duplication isn't solution. I think. How can I improve this part, besides to move this two array in bower.js file ?
Maybe you can use config.js. Use var config = require('../config'); to read the variables in config.js so you can separate file paths and task.
If you want to separate .js and .min.js , you can use
'src' : [
'src/**/*.js',
'!src/**/*.min.js',
]
For example below I concat .min.js / .js files and uglify it, and also concate .css files and use cssnano() to compress it. In the end vendor task will output vendor.bundle.js and vendor.bundle.css
config.js:
'use strict';
module.exports = {
'vendor': {
'scripts': {
'src': [
'bower_components/jquery/dist/jquery.min.js',
'bower_components/lodash/dist/lodash.min.js',
// Moment
'bower_components/moment/min/moment.min.js',
'bower_components/moment/locale/zh-tw.js',
// Ionic & Angular
'bower_components/ionic/js/ionic.bundle.min.js',
'bower_components/ngCordova/dist/ng-cordova.min.js'
// ...
],
'dest': 'www/js',
'output': 'vendor.bundle.js'
},
'styles': {
'src': [
// Mobiscroll
'bower_external/mobiscroll/css/mobiscroll.custom-2.17.0.min.css',
],
'dest': 'www/css',
'output': 'vendor.bundle.css'
}
}
}
}
vendor.js
'use strict';
var config = require('../config');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var cssnano = require('cssnano');
var handleErrors = require('../util/handleErrors');
var browserSync = require('browser-sync');
var pkg = require('../../package.json');
gulp.task('vendorScripts', function () {
return gulp.src(config.vendor.scripts.src)
.pipe(concat(config.vendor.scripts.output))
.pipe(uglify())
.pipe(gulp.dest(config.vendor.scripts.dest));
});
gulp.task('vendorStyles', function () {
return gulp.src(config.vendor.styles.src)
.pipe(concat(config.vendor.styles.output))
.pipe(postcss([ cssnano() ]))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.vendor.styles.dest));
});
gulp.task('vendor', ['vendorScripts', 'vendorStyles']);

gulp-concat twice the content

That's a weird thing for me, i have a task to concat my .js files and then uglify them with a watcher, but the concat task just twice the content in every call...
Here is my gulpfile:
'use strict';
let gulp = require('gulp');
let stylus = require('gulp-stylus');
let sourcemaps = require('gulp-sourcemaps');
let concat = require('gulp-concat');
let uglify = require('gulp-uglify');
let plumber = require('gulp-plumber');
let bootstrap = require('bootstrap-styl');
let rupture = require('rupture');
let copy = require('gulp-copy2');
/*
Prepare the paths
*/
let base = './theme';
let themeName = 'own-theme';
let paths = {
stylus : `${base}/${themeName}/css`,
js : `${base}/${themeName}/js`,
vendor : `${base}/${themeName}/js/vendor`
}
/*
Stylus compile
*/
gulp.task('stylus-compile', () => {
return gulp.src([`${paths.stylus}/dev/*.styl`, `${paths.stylus}/!**/_*.styl`])
.pipe(plumber())
.pipe(stylus({
use: [bootstrap(), rupture()],
compress: true
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(`${paths.stylus}`));
});
/*
Get the bootstrap-styl js files and concat/uglify them
*/
gulp.task('bootstrap-build', () => {
return gulp.src([
'node_modules/bootstrap-styl/js/transition.js',
'node_modules/bootstrap-styl/js/alert.js',
'node_modules/bootstrap-styl/js/button.js',
'node_modules/bootstrap-styl/js/carousel.js',
'node_modules/bootstrap-styl/js/collapse.js',
'node_modules/bootstrap-styl/js/dropdown.js',
'node_modules/bootstrap-styl/js/modal.js',
'node_modules/bootstrap-styl/js/tooltip.js',
'node_modules/bootstrap-styl/js/popover.js',
'node_modules/bootstrap-styl/js/scrollspy.js',
'node_modules/bootstrap-styl/js/tab.js',
'node_modules/bootstrap-styl/js/affix.js'
])
.pipe(sourcemaps.init())
.pipe(concat('bootstrap.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(`${paths.vendor}`));
});
/*
Get the js assets from NPM
*/
gulp.task('js-copy', () => {
let dirs = [
{ src: 'node_modules/jquery/dist/jquery.min.js', dest: `${paths.vendor}/jquery.min.js` },
{ src: 'node_modules/sweet-scroll/sweet-scroll.min.js', dest: `${paths.vendor}/sweet-scroll.min.js` }
]
return copy(dirs);
});
/*
Concat/Uglify the JS files
*/
gulp.task('js-build', () => {
return gulp.src(`${paths.js}/*.js`)
.pipe(sourcemaps.init())
.pipe(concat('site.min.js'))
// .pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(`${paths.js}`));
})
/*
Watch
*/
gulp.task('watch', () => {
gulp.watch(`${paths.js}/*.js`, ['js-build']);
gulp.watch(`${paths.stylus}/dev/*.styl`, ['stylus-compile']);
});
gulp.task('default', ['bootstrap-build', 'js-copy', 'watch']);
The bootstrap-build task don't twice the content no matter how many times you call the task, but the js-build does.
Here are the test separated scripts to concat and the results:
File 1:
(function() {
console.log("oh!")
console.log("uh!")
}).call(this);
File 2:
(function() {
console.log("hey")
}).call(this);
Concated file(uh, oh file re-saved after the watcher was fired):
(function() {
console.log("oh!")
console.log("uh!")
}).call(this);
(function() {
console.log("oh!")
console.log("uh!")
}).call(this);
(function() {
console.log("hey")
}).call(this);
//# sourceMappingURL=site.min.js.map
(function() {
console.log("hey")
}).call(this);
//# sourceMappingURL=site.min.js.map
In every re-save, the concat twice the content... i really don't get the problem. Any idea?
Thanks in adnvance.
The reason your bootstrap-build works is because it places the resulting bootstrap.min.js in a different folder than the source files.
Your js-build task however concatenates all .js files in your path.js folder and places the resulting site.min.js in that same folder.
That means when first running js-build the files file1.js and file2.js are concatenated into site.min.js. On a second run the files file1.js, file2.js and site.min.js are concatenated into site.min.js. Every time you run your js-build task your site.min.js grows.
What you need to do is exclude site.min.js from being concatenated with the other files:
gulp.task('js-build', () => {
return gulp.src([
`${paths.js}/*.js`,
`!${paths.js}/site.min.js`
])
.pipe(sourcemaps.init())
.pipe(concat('site.min.js'))
// .pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(`${paths.js}`));
})

gulp.watch doesn't catch a new files

I have the following gulpfile
var gulp = require('gulp');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var coffee = require('gulp-coffee');
var cache = require('gulp-cached');
var path = require('path');
var dist = './Test/public/';
var assets = './Test/assets/';
var paths = {
coffee: ['./**/*.coffee']
};
var coffeeTask = function () {
console.log('coffeeTask');
return gulp.src(paths.coffee, { cwd: assets + '**' })
.pipe(cache('coffee'))
.pipe(coffee({ bare: true }))
.pipe(rename({
extname: ".coffee.js"
}))
.pipe(gulp.dest(dist));
};
gulp.task('clean', function() {
return gulp.src(dist)
.pipe(clean());
});
gulp.task('coffee', ['clean'], coffeeTask);
gulp.task('coffee-watch', coffeeTask);
gulp.task('build', ['clean', 'coffee']);
gulp.task('watch', ['build'], function() {
var w = gulp.watch(paths.coffee, ['coffee-watch']);
w.on('change', function(evt) {
console.log(evt);
});
});
gulp.task('default', ['build']);
The key point of this configuration is use the same tasks for deploy and watch processes (read "build" and "watch" tasks).
The problem is that watch task doesn't catche any new coffee files. Edited or removed coffee files are processed well. According the following issue it should works. What the reason is?
Solved by using gulp-watch module:
watch(paths.coffee, function(evt) {
gulp.start('coffee-watch');
});
The question no is how to remove in dist folder deleted file in assets folder?

Categories