Cannot use vinylPaths del with gulp - javascript

I have the following gulp task, basically what it does is:
compile all .styl files
put the result in theme/app folder
minify all file in theme/app folder
concatenate all file in folder theme/app folder to a single file
add some license information to the file
save result in foldertheme
delete all files in theme/app folder
I cannot make work the last step, I need to delete all files in theme/app.
I have not specific error, what could could be wrong in my script and how to solve it?
gulp.task('_release-theme:compile', function () {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.pipe(vinylPaths(del['theme/app/**/*'])); // problem here
});

del is a function. Your object property access del['theme/app/**/*'] makes no sense here.
Instead listen for the end event in your stream and then delete the files using rimraf:
var rimraf = require('rimraf');
gulp.task('_release-theme:compile', function (done) {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.on('end', function() {
rimraf('theme/app/**/*', done);
});
});

Related

Gulp is compiling every Js-file

i have a problem with my gulp.
Its works fine and its really fast but Gulp is compiling all js files in my project...
my gulp-watch:
gulp.task('watch', function () {
gulp.watch(sassFilesWatch, ['styles']);
gulp.watch(jsFilesWatch, ['uglify'])
});
My array:
var jsFilesWatch = [
'clients/*/template/lib/jscripts/*.js',
'clients/*/template/modules/**/*.js',
'system/lib/jscripts/*.js',
'system/mod/**/*.js',
'clients/core/modules/**/*.js',
'!/**/*.min.js'
];
Thats my function:
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
And thats the output:
Output
Just my saved file should be compiled
how can i do that?
thanks alot
It seems all your files with .js extensions are
being debugged, uglified and minified.
Which saved file are you trying to compile?
**/*.js uses the gulp command to watch all files with the .js extension in all folders.
You could use .pipe()
var uglify = require('gulp-uglify'),
concat = require('gulp-concat');
gulp.task('js', function() {
gulp.src('scripts/*.js')
.pipe(uglify())
.pipe(concat('script.js'))
.pipe(gulp.dest('assets'))
});
Have a look into this Plugin, That will solve your problem
https://www.npmjs.com/package/gulp-changed
Try Changing your task to,
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
changed('dist'),
ngAnnotate(),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
Note: this might run all your .js files at first time after you run your task, but it will identify the changed file on subsequent runs

Excluding a file change in gulp but still keeping the file

The following is my simple gulp task:
gulp.src is getting script.js as input
minifies script.js and saves script.min.js
removes console.log from both script.js and script.min.js
updates script.js file and saves script.min.js
I want to simply remove console.log from a minified file (or script.min.js) not from script.js, and I am failing. I am looking for a way to run .pipe(gulpRemoveLogging... only on a minified file (i.e. script.min.js) and do not modify anything from script.js
var gulp = require("gulp"),
minify = require("gulp-minify"),
gulpRemoveLogging = require("gulp-remove-logging");
var _dist_path = "./dist/"; // relative path
// minify JS files
gulp.task("minify-js", function() {
return gulp.src(path.join(_dist_path, "/*.js"))
.pipe(minify({
ext: {
src: ".js",
min: ".min.js"
},
ignoreFiles: ["-min.js"]
}))
.pipe(gulpRemoveLogging({
namespace: ["console", "window.console"] // remove these namespaces. e.g. console.log("..."), window.console.log("...")
}))
.pipe(gulp.dest(_dist_path));
});
Solved the problem:
Added .pipe(gulpIgnore("smartsitescripts.js")) between .pipe(minify({ ... and .pipe(gulpRemoveLogging ...
var gulpIgnore = require("gulp-ignore");
...
.pipe(minify({
ext: {
src: ".js",
min: ".min.js"
},
ignoreFiles: ["-min.js"]
}))
.pipe(gulpIgnore("script.js")) // <---- this line solved the problem
.pipe(gulpRemoveLogging({
namespace: ["console", "window.console"] // remove these namespaces. e.g. console.log("..."), window.console.log("...")
}))
...
That line of code will exclude script.js from stream hence stream will contain only script.min.js.

Gulp-sourcemaps returning only returning `source` js file

My sourcemaps are only returning the source value no matter what.
Broswerify.js
// add custom browserify options here
var customOpts = {
entries: ['./frontend/js/app.js'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
b.transform(require("jadeify"), { compileDebug: true, pretty: false });
// add transformations here
// i.e. b.transform(coffeeify);
gulp.task('browserify', 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('main.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('./public/js'))
.on('end', function () {
browserSync.reload();
});
}
main.js.map
{"version":3,"sources":["/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;
This of course means that all files are referenced as main.js which is less then helpful :(
I am also using browser-sync, but I don't believe this has any effect on sourcemaps.
I was using gulp-sourcemaps v2.3.0
Upgraded to v2.6.0 and now its working. I thank you sir

Concatenated files put into main.js just keeps stacking instead of clearing the file then adding the code

I'm trying to compile all my scripts into a single main.js file which I can then link to my index file. Problem is that all my script files are being concatenated and then just added to the main.js file, so if I save 3 times, I will basically have 3 copies of all my scripts concatenated and put in the main.js file.
I would like to either delete the main.js file each time I save and then run the concatenation, or just clean the file before adding the contents. Now if I try to delete the file using the del module, I receive an error stating that I can't delete files out of the working directory without forcing this action. I would like to avoid forcing this if possible.
I feel that there must be a more elegant way of doing this..
Here's my script task:
// Concat and compile our JS into a minified dist file
gulp.task('scripts', function() {
return gulp.src('../app/public/assets/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(concat('main.js'))
//.pipe(del(['../app/public/assets/scripts/main.js'])) <-- Doesn't work without forcing
.pipe(gulp.dest('../app/public/assets/scripts'))
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(notify({ message: 'Finished compiling scripts' }));
});
I usually do something like this (very simplified :) ):
var PARAMS = {
destPath: 'build',
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
],
// other
};
var TARGETS = {
dest: 'main.js', // dest file
extra: [
// This files are inclued only in .bundle.min.js version
// extra file here
],
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
]
};
gulp.task('connect', function() {
return connect.server({
livereload: true,
host: '0.0.0.0',
port: 8000
});
});
gulp.task('reload', ['build'], function () {
return gulp.src(['sandbox/**/*.html'])
.pipe(connect.reload());
});
gulp.task('watch', ['connect', 'build'], function () {
var src = [];
// other
src = src.concat(PARAMS.js);
return gulp.watch(src, ['reload']);
});
gulp.task('clean', function (done) {
return del(['build'], done);
});
gulp.task('build', ['clean'], function () {
return gulp.src(target.js);
.pipe(concat(target.dest))
.pipe(gulp.dest(PARAMS.destPath)) // Plain
.pipe(uglify())
.pipe(rename({ extname: '.min.js' })) // Minified
.pipe(gulp.dest(PARAMS.destPath))
.pipe(addsrc(target.extra))
.pipe(order(target.extra))
.pipe(concat(target.dest))
.pipe(rename({ extname: '.bundled.min.js' })) // Bundled
.pipe(gulp.dest(PARAMS.destPath));
});
gulp.task('default', ['build']);

make some operations on factor-bundle's partial bundles

I am using gulp with browserify and factor-bundle.
I have the following code:
b = browserify({
entries: [ 'a.js', 'b.js'],
plugin: [ [ 'factor-bundle', { outputs: [ 'build/a.js', 'build/b.js' ] } ] ]
})
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(gulp.dest('/build/common'));
I want to pipe some actions (like uglify, bundle-collapser or other job) on the parial bundles ('build/a.js' and 'build/b.js'). I tried to use the method described on the factor-bundle's page:
b.plugin('factor-bundle', { outputs: [ write('x'), write('y') ] });
function write (name) {
return concat(function (body) {
console.log('// ----- ' + name + ' -----');
console.log(body.toString('utf8'));
});
}
But I don't understand the write() method and don't know how to perform uglification and how to gulp.dest the result.
Any idea? explanation?
The write() method returns a writable stream that allows you to pipe bundles
generated by the factor-bundle plugin through further downstream transformations.
For instance, your write() method may look something like this:
var path = require('path');
var file = require('gulp-file');
var sourcemaps = require('gulp-sourcemaps');
function write (filepath) {
return concat(function (content) {
// create new vinyl file from content and use the basename of the
// filepath in scope as its basename.
return file(path.basename(filepath), content, { src: true })
// uglify content
.pipe(uglify())
// write content to build directory
.pipe(gulp.dest('./build/scripts'))
});
}
And you would use it like this:
browserify({
entries: [ 'a.js', 'b.js'],
plugin: [ [ 'factor-bundle', { outputs: [ write('a.js'), write('b.js') ] } ] ]
})
.bundle()
.pipe(write('common.js'))
// Could have use these instead, but it wouldn't be as DRY.
// .pipe(source('common.js'))
// .pipe(uglify())
// .pipe(gulp.dest('./build/scripts'))
Using the factor-bundle plugin affects the output of browserify after
.bundle() is called. Normally, it would generate bundles as readable streams
mapping to each of your entry files, then you would be able to apply further
transformations to them.
Instead you will get a single readable stream that contains a bundle with the
shared common modules from the supplied entry files, which I have called
common.js on the example above. Then you need to handle the transfomations
of the readable streams that map to each entry file separately.
In the example above I have added writable streams to the outputs array, arranged
in the same order as my entry files, which receive their respective bundle as
readable stream and apply further transformations to them
You could also leverage the factor.pipeline event:
var b = browserify({ ... });
b.on('factor.pipeline', function (id, pipeline) {
pipeline.get('wrap').push(write(id));
});
b.plugin(factor);
return b.bundle().pipe(write('common.js'));
I think it is worth noting that applying further downstream work to the outputs
is completely detached from the pipeline. So if you were using gulp and returned
the stream from browserify, the task would have completed prematurely because
it would still be performing operations on the entry files. I haven't run into
issues with this yet.
Hope this helps.
This is a bit old, but it might be usefull to someone else.
The answer above from #Christian helped me, but i had to solve the issue of the task completion. I did it by adding a counter for opened streams, and calling the task callback once they are all closed.
gulp.task('build:js:compile', function(cb) {
const apps = getAllJavascriptFilesPaths(); // this returns an array of full path to the js files i want to bundle
const dist = 'dist'; // the output path
const files = [];
const streams = [];
let openedStreams = 0;
// We use browserify factor-bundle to get the shared code in a separated js file, and not in all apps files
// The write function here handles the post processing of each browserified app by returning a writable stream
// We check the number of opened streams, and call the callback once they are all closed, to be sure the task is
// complete
function write(filepath) {
openedStreams++;
return concat(function (content) {
// create new vinyl file from content and use the basename of the
// filepath in scope as its basename.
return file(path.basename(filepath), content, { src: true })
.pipe(uglify())
.pipe(gulp.dest(dist))
.on('finish', function () {
openedStreams--;
if (openedStreams == 0) {
cb();
}
});
});
}
apps.forEach(function (file) {
files.push(file);
streams.push(write(file)));
});
browserify(files)
.plugin(factor, { outputs: streams })
.transform("babelify", {presets: 'babel-preset-env'})
.bundle()
.pipe(write('common.js'));
});

Categories