Gulp rollup in parrallel task and series - gulp

I have a gulpfile as below with a rollupTask. But at the last task which zipTask, it output without bundled js from rollup. The only way i found that fix this is to add wait time before the ziptask. There seems to be a fraction of delay with rollup output and the next gulp series. Is this the expected behavior or there is something that fix this without add waiting time ? Is my rollupTask is correct ? the zip tasks simply zip the output folder into a different folder. The output folder itself contain the expected bundle.
const gulp = require('gulp');
const rollup = require('rollup');
async function rollupTask() {
const rollupBuild = await rollup({
input: 'index.js',
plugins: rollupPlugins,
});
await rollupBuild.write({
file: 'bundle.js',
format: 'es',
sourcemap: true,
});
await rollupBuild.close();
}
exports.default = series(taskOne, parallel(taskTwo, taskThree, rollupTask), zipTask);

The easiest way is to use a plugin written for gulp. gulp-rollup
const { src, dest } = require('gulp');
const rollup = require('gulp-rollup');
function rollupTask() {
const options = { input: './src/main.js' } // any option supported by Rollup can be set here.
return src('./src/**/*.js')
.pipe(rollup(options)) // transform the files here.
.pipe(dest('./dist'));
}
exports.build = series(rollupTask);
On start: gulp build

Related

Check if file contains a specific string in GULP

I am attempting to use GULP4 to compress a series of HTML and PHP files. A problem I am running into is some of the files contain a <pre> tag. I do not want to compress those files because it would mess up that file. Is there a way using GULP I can evaluate if a file contains the string <pre> and if it does, avoid running compression on that file?
Here is my relevant code:
const gulp = require('gulp');
const {src, series, parallel, dest} = require('gulp');
const GulpReplace = require('gulp-replace');
function no_2_spaces_purchasingdemand_php()
{
console.log("no 2 spaces purchasingdemand_php")
return gulp.src
(
'dist/purchasingdemand/**/*.php'
, { base: "./" }
)
.pipe
(
GulpReplace(' ','☺☻')
)
.pipe
(
GulpReplace('☻☺','')
)
.pipe
(
GulpReplace('☺☻',' ')
)
.pipe(gulp.dest('./'))
}
exports.default = series(no_2_spaces_purchasingdemand_html)
I don't know what you are using to compress files, but here is a general example:
const gulp = require('gulp');
const filter = require('gulp-filter');
const minify = require('gulp-htmlmin');
gulp.task("preFilterTask", function () {
// return true if want the file in the stream
const preFilter = filter(function (file) {
let contents = file.contents.toString();
return !contents.match('<pre>');
});
return gulp.src("./*.html")
.pipe(preFilter)
.pipe(minify({ collapseWhitespace: true }))
.pipe(gulp.dest('filtered'));
});
gulp.task('default', gulp.series('preFilterTask'));
gulp-htmlmin by itself - for html files only - will not minify the <pre>...</pre> portion of an html file. So if you use gulp-htmlmin for html minification, you don't need to filter out those with <pre> tags.
I still showed how to filter based on file content using the gulp-filter plugin. It can access each file's contents. Return false from the filter function if you do not want that file to pass to the next pipe.

Why is Gulp concatenating my output in the wrong order?

As shown in the following gulpfile.js, I am trying to compile jQuery, bootstrap.js, and a collection of Javascript snippets from a subfolder into a single app.js output file. It is working, except that the snippets from the subfolder are appearing at the top of the app.js output file, prior to jQuery being loaded.
How can I ensure that these files are output in the correct order?
const { src, dest, watch, series, parallel } = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
var merge2 = require('merge2');
const files = {
jsSrcPath: [
'../node_modules/jquery/dist/jquery.js',
'../node_modules/bootstrap/dist/js/bootstrap.js',
'js/*.js'
],
jsDstPath: '../public/js'
}
function jsTask(){
return merge2(files.jsSrcPath.map(function (file) {
return src(file)
}))
.pipe(concat('app.js'))
.pipe(uglify())
.pipe(dest(files.jsDstPath));
}
function watchTask(){
watch(files.jsSrcPath, jsTask);
}
exports.default = series(
jsTask,
watchTask
);
There's something internal here going on, in my tests I saw the order was sometimes random, sometimes based on modification time, sometimes in order. In any case, best to use a tool to ensure our streams are always in the order we want them.
gulp-order exists for this purpose. It can take specific paths and glob syntax, which you already have, so you can re-pass that to the plugin:
const { src, dest, watch, series, parallel } = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const order = require('gulp-order'); // Added
var merge2 = require('merge2');
const files = {
jsSrcPath: [
'../node_modules/jquery/dist/jquery.js',
'../node_modules/bootstrap/dist/js/bootstrap.js',
'js/*.js'
],
jsDstPath: 'dist'
}
function jsTask() {
return merge2(files.jsSrcPath.map(function (file) {
return src(file)
}))
.pipe(order(files.jsSrcPath)) // Added
.pipe(concat('app.js'))
.pipe(uglify())
.pipe(dest(files.jsDstPath));
}
function watchTask() {
watch(files.jsSrcPath, jsTask);
}
exports.default = series(
jsTask,
watchTask
);

Gulp default task unable to compress after copy

At first I thought this was related to dependency of tasks so I went with run-sequence and even tried defining dependencies within tasks themselves. But I cannot get the compress task to run after copy. Or, even if it says it did finish the compress task, the compression only works if I run compress in the task runner inside visual studio by itself. What else can I try to get it to compress after copy?
/// <binding BeforeBuild='default' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. https://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require("gulp");
var debug = require("gulp-debug");
var del = require("del");
var uglify = require("gulp-uglify");
var pump = require("pump");
var runSequence = require("run-sequence");
var paths = {
bower: "./bower_components/",
lib: "./Lib/"
};
var modules = {
"store-js": ["store-js/dist/store.legacy.js"],
"bootstrap-select": [
"bootstrap-select/dist/css/bootstrap-select.css",
"bootstrap-select/dist/js/bootstrap-select.js",
"bootstrap-select/dist/js/i18n/*.min.js"
]
}
gulp.task("default", function (cb) {
runSequence("clean", ["copy", "compress"], cb);
});
gulp.task("clean",
function () {
return del.sync(["Lib/**", "!Lib", "!Lib/ReadMe.md"]);
});
gulp.task("compress",
function (cb) {
pump([
gulp.src(paths.lib + "**/*.js"),
uglify(),
gulp.dest(paths.lib)
], cb);
});
gulp.task("copy",
function (cb) {
prefixPathToModules();
copyModules();
cb();
});
function prefixPathToModules() {
for (var moduleIndex in modules) {
for (var fileIndex in modules[moduleIndex]) {
modules[moduleIndex][fileIndex] = paths.bower + modules[moduleIndex][fileIndex];
}
}
}
function copyModules() {
for (var files in modules) {
gulp.src(modules[files], { base: paths.bower })
.pipe(gulp.dest(paths.lib));
}
}
You use run-sequence and your code
runSequence("clean", ["copy", "compress"], cb);
run in such order
clean
copy and compress in parallel // that's why your code compresses nothing, because you have not copied files yet
cb
Write like this and compress will be after copy
runSequence("clean", "copy", "compress", cb);
I am not familiar with runSequence. But why don't you try the following. By this way your default task depends on compress and compress depends on copy. So, 'copy' will run first and then 'compress'
gulp.task('default', ['copy','compress'], function(cb){});
gulp.task('compress',['copy'], function(cb){});
Gulp returns a steam , since you are calling it in a for loop the stream is returned during the first iteration itself.
Update your copyModule to the following and you can try either runSequence like posted by Kirill or follow my approach
function copyModules() {
var inputFileArr = [];
for (var files in modules) {
inputFileArr = inputFileArr.concat(modules[files]);
};
return gulp.src(inputFileArr, { base: paths.bower })
.pipe(gulp.dest(paths.lib));
}

gulpfile.js: rev.manifest() not merging several JS tasks

The code bellow doesn't merge correctly rev-manifest.json file.
I loop several JS tasks and just one is merged, although hash files are being created and stored correctly.
I already tried a ton of things, I checked gulp-rev and some users seam to have similar problems. Some of them are creating several manifest files and proceed with the actual merge at the end. I would like to discard this solutions since it's slow and ugly.
If I comment the concat(...) line the manifest file registers all the JS tasks.
Is this a BUG or am I missing something here?
gulp 3.9.1
gulp-concat 2.6.0
gulp-rev 7.0.0
var gulp = require('gulp');
var less = require('gulp-less');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var rev = require('gulp-rev');
var jsFiles = {
task1: [
'./path/file1.js'
],
task2: [
'./path/file2.js',
'./path/file2.js'
]
};
function jsTask(key) {
gulp.task(key, function() {
gulp.src(jsFiles[key])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
// IT WORKS WHEN I COMMENT THIS LINE
.pipe(concat(key + '.min.js'))
.pipe(rev())
.pipe(gulp.dest('./public/js'))
.pipe(rev.manifest({merge:true }))
.pipe(gulp.dest('.'));
});
}
gulp.task('less', function() {
return gulp.src(['./path/less/*.less'])
.pipe(less({errLogToConsole: true}))
.pipe(minifycss())
.pipe(rev())
.pipe(gulp.dest('./path/public/css'))
.pipe(rev.manifest({merge:true }))
.pipe(gulp.dest('.'));
});
for (var key in jsFiles) {
jsTask(key);
}
var defaultTasks = ['less'];
for (var key in jsFiles) {
defaultTasks.push(key);
}
gulp.task('default', defaultTasks);
You can pass the name of the manifest file you want to create(different for each gulp task) to manifest function of the gulp-rev-all module like below
gulp.task('productionizeCss', function () {
return gulp
.src(['dist/prod/**/*.css'])
.pipe(revAll.revision({
fileNameManifest: 'css-manifest.json'
}))
.pipe(gulp.dest('dist/prod/'))
.pipe(revAll.manifestFile())
.pipe(gulp.dest('dist/prod/'));
});
gulp.task('productionizeJS', function () {
return gulp
.src(['dist/prod/**/*.js'])
.pipe(revAll.revision({
fileNameManifest: 'js-manifest.json'
}))
.pipe(gulp.dest('dist/prod/'))
.pipe(revAll.manifestFile())
.pipe(gulp.dest('dist/prod/'));
});
Here, I have two gulp tasks, one to revise all JS and one for CSS.So, I have created two manifest files css-manifest.json, js-manifest.json.
Then I specified both the manifest files in src of the rev-replace module as shown below:
gulp.task('revReplaceIndexHtml', function () {
var manifest = gulp.src(["dist/prod/js-manifest.json", 'dist/prod/css-manifest.json']);
return gulp.src('dist/dev/referralswebui/index.html')
.pipe(revReplace({ manifest: manifest, replaceInExtensions: ['.html']}))
.pipe(gulp.dest('dist/prod/referralswebui/'));
});
I would suggest using gulp-useref instead of gulp-concat.
Given your setup, I think key references a glob path, or at least I hope so. Otherwise you are trying to concatenate a single file, or no files which may crash the concat plug-in. Emphasis on may.
Also, since you are using gulp-rev, I suggest using gulp-rev-replace which will automatically update your index references to the reved files.
Edit
Sometimes rev.manifest behaves in ways that I would describe as buggy. Just to exhaust all possibilities remove the merge option for the manifest and run concat. Or run concat and remove manifest altogether.

Gulp Browserify with glob and uglify/factor-bundle

I'm currently getting into browserify. I like it so far but before I start using it I want to automate it. Gulp is the build system of my choice.
So what I actually want to do is:
Get js/app/**.js, bundle it to js/bundle/ and extract common dependencies into js/bundle/common.js. In addition uglify everything and add source maps.
Well. The gulp support for browserify kinda seems poor, at least my google researches were pretty disappointing.
Anyway. What I've got so far.
var gulp = require('gulp'),
browserify = require('browserify'),
factor = require('factor-bundle');
// ...
// gulp task
return browserify({
entries: ['js/app/page1.js', 'js/app/page2.js'],
debug: true
})
.plugin(factor, {
o: ['js/bundle/page1.js', 'js/bundle/page2.js']
})
.bundle()
.pipe(source('common.js'))
.pipe(gulp.dest('js/bundle/'));
Well this is neither uglifying nor adding sourcemaps and much less using a glob pattern. I can find an official recipe which shows me how to use the pipe to add additional transformations like uglify. But it's only for a single file.
as an outputs parameter to factor-bundle, use streams instead of file paths. You can do whatever you want with the streams then.
var indexStream = source("index.js");
var testStream = source("tests.js");
var commonStream = bundler.plugin('factor-bundle', { outputs: [indexStream, testStream] })
.bundle()
.pipe(source('common.js'));
return merge(indexStream, commonStream, testStream)
.pipe(buffer())
.pipe(sourcemaps.init({ debug: true, loadMaps: true }))
.pipe(uglify())
.pipe(gulp.dest('js/bundle/'))
Thanks to Liero's answer, I got something very similar working. Here's the complete gulpfile:
const gulp = require('gulp');
const browserify = require('browserify');
const factor = require('factor-bundle');
const source = require('vinyl-source-stream');
const sourcemaps = require('gulp-sourcemaps');
const buffer = require('gulp-buffer');
const merge = require('gulp-merge');
gulp.task('bfb', function () {
const fejs = 'public/javascripts/' // location of source JS
const fejsb = fejs + 'b/'; // location of bundles
const modules = [ // aka entry points
'accounts',
'invoice',
'invoices',
// etc...
];
const inputs = [];
const streams = [];
modules.forEach(function (module) {
inputs.push(fejs + module + '.js');
streams.push(source(module + '.js'));
});
const bundler = browserify(inputs, {});
const commonStream = bundler.plugin(factor, { outputs: streams })
.bundle()
.pipe(source('common.js'));
streams.push(commonStream);
return merge(streams)
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
//.pipe(uglify()) // haven't tested this bit
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(fejsb));
});