Why Gulp does not ignore the file? - node.js

My project structure:
build
public
assets
css
app.css
vendor.css
js
app.js
vendor.js
index.html
src
assets
styles
main.styl
coffee
main.coffee
index.jade
I have a task to build a library of Bower in two files : vendor.css and vendor.js:
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var mainBowerFiles = require('gulp-main-bower-files');
var filter = require('gulp-filter');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
gulp.task('bower', ['clean'], function () {
var jsFilter = filter('**/*.js', { restore: true });
var cssFilter = filter('**/*.css', { restore: true });
return gulp.src('./bower.json')
.pipe(mainBowerFiles())
.pipe(cssFilter)
.pipe(concat('vendor.css'))
.pipe(minifyCss())
.pipe(gulp.dest(path.dist.css))
.pipe(cssFilter.restore)
.pipe(jsFilter)
.pipe(concat('vendor.js'))
.pipe(uglify())
.pipe(gulp.dest(path.dist.js))
.pipe(jsFilter.restore)
.pipe(connect.reload());
});
Here's my task on cleaning of temporary folders when you change files in the src folder:
var del = require('del');
...
gulp.task('clean', function () {
return del(['build', 'public/**', '!public/**/vendor.{js,css}']);
});
That must delete the build folder and all the contents of the public directory, except the vendor.css and vendor.js that are in the folder public/assets/css and public/assets/js.
This is done in order to not build a library of bower at each change of the file, because it takes 3-4 seconds (by the way, is this normal?), but only at the first start or change bower.json ( running separate watcher).
But somehow, the files vendor.js and vendor.css also removed. With gulp-tap I got a list of files:
List of files
What am i doing wrong?

According to https://github.com/sindresorhus/del#beware you need also exclude sub-directories, otherwise del will delete all.
So, you can use something like this:
del([.., 'public/**/*', '!public/{dir_1,dir_2}', '!test/**/vendor{.css,.js}']);

Related

Node.js Gulp no outputfile created

I have a Gulp script to concatenate, and minimize javascript.
It seems to be working but doesn't output the combined file.
The script is (complete - including extra debug bits):
// include plug-ins
var fs = require('fs');
var gulp = require('gulp');
var count = require('gulp-count');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var config = {
src: 'dist/libraries/',
dest: 'dist/js/',
outputfile: 'libraries.min.js'
}
gulp.task('read', (done) => {
fs.readdir(config.src, (err, items) => {
console.log(items);
});
done();
});
//delete the output file(s)
gulp.task('clean', gulp.series('read'), (done) => {
//del is an async function and not a gulp plugin (just standard nodejs)
//It returns a promise, so make sure you return that from this task function
// so gulp knows when the delete is complete
return del([config.dest + config.outputfile]);
});
// Combine and minify all files from the app folder
// This tasks depends on the clean task which means gulp will ensure that the
// Clean task is completed before running the scripts task.
gulp.task('scripts', gulp.series('clean'), (done) => {
//Include all js files but exclude any min.js files
var files = [config.src + '*.js', '!' + config.src + '*.min.js'];
return gulp.src(files)
.pipe(debug())
.pipe(count('## files selected'))
.pipe(uglify())
.pipe(concat(config.outputfile))
.pipe(gulp.dest(config.dest));
});
//Set a default tasks
gulp.task('default', gulp.series('scripts'), (done) => {
});
Which produces the output - including file list for verification there are src files:
[07:46:25] Using gulpfile <path>\gulpfile.js
[07:46:25] Starting 'default'...
[07:46:25] Starting 'scripts'...
[07:46:25] Starting 'clean'...
[07:46:25] Starting 'read'...
[07:46:25] Finished 'read' after 996 μs
[07:46:25] Finished 'clean' after 2.73 ms
[07:46:25] Finished 'scripts' after 4.26 ms
[07:46:25] Finished 'default' after 6.9 ms
[ 'bootstrap-datetimepicker.js',
'bootstrap.min.js',
'chart.min.js',
'cycle.js',
'farbtastic.js',
'jquery-3.2.1.min.js',
'jquery-sortable-min.js',
'moment.min.js',
'ol.min.js',
'pablo.min.js',
'popper.min.js',
'proj4.js',
'promisedIndexDB.js',
'qunit-2.6.1.js',
'toastr.js' ]
If I create an empty file, at dist/js/libraries.min.js it isn't deleted as part of the gulp tasks, however if i move the call to del() outside the gulp tasks it is deleted, so that leads me to assume that its not as simple as a permissions issue, or path issues.
Any idea what I've done wrong?
PS: its on a windows box, running in an admin cmd window.
You were using the wrong signature for the task. The correct one is :
task([taskName], taskFunction)
see task signature
But your tasks look like this:
gulp.task('scripts', gulp.series('clean'), (done) => { // 3 parameters
Merely changing that to:
gulp.task('scripts', gulp.series('clean', (done) => {
...
}));
makes it work - I tested it. So now that task has only two parameters: a task name and a function. Yours had a task name plus two functions.
You would also need to change your default and clean tasks to this proper signature. Also you should call done() at the end of the task as you did with your cb().
Your new code uses task functions, which are better than named tasks for a number of reasons - but now you know what was wrong with your original code. The main body of your scripts task was never being run.
I never worked out what was wrong, but went direct to the doc's and started again (previous version was from a example)..
Works with the below (much simpler) script.
// // include plug-ins
var gulp = require('gulp');
var count = require('gulp-count');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var config = {
src: 'jspa-scada/dist/libraries/',
dest: 'jspa-scada/dist/js/',
outputfile: 'libraries.min.js'
}
function defaultTask(cb) {
del([config.dest + config.outputfile]);
// Include all js files but exclude any min.js files
var globs = [
config.src + '*.js',
'!' + config.src + '*.min.js'
];
return gulp.src(globs)
.pipe(debug())
.pipe(count('## files selected'))
.pipe(uglify())
.pipe(concat(config.outputfile))
.pipe(gulp.dest(config.dest));
cb();
}
exports.default = defaultTask

require is not defined error on gulp-concat

I want to uglify and combine my js files with gulp. Here is my code
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pump = require('pump');
var gutil = require('gulp-util');
gutil.env.type = 'production';
gulp.task('uglify', function (cb) {
return gulp.src([
'pure/modernizr.js',
'pure/horizon.js'
])
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest("ugly"));
});
var sourcemaps = require("gulp-sourcemaps");
var concat = require("gulp-concat-js");
gulp.task("concat", function () {
return gulp.src([
'ugly/modernizr.js',
'ugly/horizon.js'
])
.pipe(sourcemaps.init())
.pipe(concat({
"target": "concatenated.js", // Name to concatenate to
"entry": "./main.js" // Entrypoint for the application, main module
// The `./` part is important! The path is relative to
// whatever gulp decides is the base-path, in this
// example that is `./lib`
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest("pure/"));
});
I end up with some code enclosing my js files from obfuscator stating:
//// THIS FILE IS CONCATENATED WITH gulp-obfuscator-js
When I include this in code, it throws require is not defined, I surf around the web and found one similar question. But that answer is also not clear for me. I believe that I miss some small thing here, since I am new to gulp.
The issue here is I have used gulp-concat-js which obfuscate your js. I should have used gulp-concat. May help someone.

Modify gulp file to run customized browserify command

I would like to use gulp to run a custom browserify command whenever a js file (function.js) is modified.
The browserify command that I want to run is;
$ browserify function.js --standalone function > bundle.js
I am using this gulpfile.js as sample.
https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md
How do I modify this gulpfile to run the customized browserify command?
'use strict';
var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
// add custom browserify options here
var customOpts = {
entries: ['./src/index.js'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
// add transformations here
// i.e. b.transform(coffeeify);
gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal
function bundle() {
return b.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
// optional, remove if you dont want sourcemaps
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
// Add transformation tasks to the pipeline here.
.pipe(sourcemaps.write('./')) // writes .map file
.pipe(gulp.dest('./dist'));
}
I am using node.js v6.9 on webstorm.
The command you want to run is;
$ browserify function.js --standalone function > bundle.js
Based on this, the modified code is;
// add custom browserify options here
var customOpts = {
entries: ['./function.js'],
standalone: 'function',
};
Simply add one more property to customOpts for the --standalone parameter. The rest of the code remains the same.

How to put the file compiled by gulp-compass into gulp's stream?

I am a newbie to gulp and gulp-compass. IMHO, gulp-compass doesn't work in the gulp's stream paradigm.
Normally, gulp's task should be something like:
gulp.src('path/to/src')
.pipe(doSth)
.pipe(gulp.dest('path/to/dist'));
But the following code works for gulp-compass:
gulp.src('') // <-Empty source is OK
.pipe(compass({
css: 'path/to/dist/css' // <- This is the output dir
scss: 'path/to/src/scss' // <- This is the input scss file glob
}));
// No dest is needed!
This results in my following problem.
|- dist
|- scss
|- app.scss
|- css
|- bootstrap.css
I want to use gulp-compass to compile app.scss into app.css, then bundle app.css with bootstrap.css, then minify and output as app-release.css.
I want to finish this task in ONE gulp.task.
function buildCss(inputStream) { // minify and output to dist.
return inputStream
.pipe(cssnano())
.pipe(gulp.dest('dist'));
}
gulp.task('css-build', function() {
var stream = gulp.src('scss/app.scss')
.pipe(compass({
css: 'css',
sass: 'scss'
}))
.pipe(gulp.src('css/*.css')); // <-- **HERE**
return buildCss(stream);
});
However, The compiled app.css file is not included in stream of HERE.
What is the solution?
I could fix this problem using merge-stream.
gulp.task('css', function() {
var scss = gulp.src('scss/*.scss')
.pipe(compass({
css: 'css',
sass: 'scss'
}));
var css = gulp.src('css/bootstrap.css');
var stream = merge(scss, css)
.pipe(concat('app-release.css'));
return buildCss(stream);
});

Looking to use Gulp to create individual distributions of standalone HTML files

Basically I'm looking for a Gulp plugin to turn a directory like this:
/app
- htmlfile1.html
- htmlfile2.html
- htmlfile3.html
- /css
-cssmain.css
-/js
-global.js
And turn that into this:
/dist
-/htmlfile1
- htmlfile1.html
- /css
-cssmain.css
-/js
-global.js
- /htmlfile2
- htmlfile2.html
- /css
-cssmain.css
-/js
-global.js
- /htmlfile3
- htmlfile3.html
- /css
-cssmain.css
-/js
-global.js
Any thoughts on how to do accomplish a build system like this?
The code allows common files to be added to every page distribution as well as unique dependencies defined as an array in the pages object.
The following Gulp file relies on gulp-foreach, parse-filepath, and event-stream: npm install gulp gulp-foreach parse-filepath event-stream --save-dev
gulpfile.js:
// Command:
// npm install gulp gulp-foreach parse-filepath event-stream --save-dev
// Include gulp
var gulp = require('gulp');
var foreach = require('gulp-foreach'); // https://www.npmjs.org/package/gulp-foreach
var parsePath = require('parse-filepath'); // https://www.npmjs.org/package/parse-filepath
var es = require('event-stream'); // https://www.npmjs.org/package/event-stream
// The pages that each make a distribution
// Unique dependencies are defined as an array value for each page.
var pages = {
'./app/htmlfile1.html': [
'./app/images/1.png',
'./app/images/1-another.png',
],
'./app/htmlfile2.html': [],
'./app/htmlfile3.html': []
};
// Files added to each page distribution
var common = [
'./app/css/cssmain.css',
'./app/js/global.js',
];
function makeDistributionStream(page)
{
var gulpStream = gulp.src(page)
.pipe(foreach(function(stream, file) {
var pathParts = parsePath(file.path);
// Assemble the distribution path
var destinationPath = './dist/' + pathParts.name + '/';
// Pipe the html into the distribution folder
stream.pipe(gulp.dest(destinationPath));
// Move all of the unique and common files into the distibution
var uniqueDependencies = pages[page];
// Merge the common files to the unique ones
var distFiles = uniqueDependencies.concat(common);
gulp.src(distFiles, {base: './app/'})
.pipe(gulp.dest(destinationPath));
}));
return gulpStream;
}
// Assemble the distribution directories for each page
gulp.task('make-distributions', function() {
var mergedStream = null;
for(var page in pages)
{
var stream = makeDistributionStream(page);
// Merge the streams, if there is already one
if(mergedStream)
{
mergedStream = es.merge(mergedStream, stream);
}
// Otherwise, just make it this one
else
{
mergedStream = stream;
}
}
return mergedStream;
});
// Rerun the task when a file changes
gulp.task('watch', function() {
// If the html pages change, re-make the distributions
gulp.watch(Object.keys(pages), ['make-distributions']);
});
// Default Task
gulp.task('default', ['make-distributions', 'watch']);

Resources