Rename Files Using Gulp w/ Specific Pattern - javascript

I have a Gulp task that needs to copy the contents from one directory to another and rename each file with a specific pattern. Basically, if I have main.css, I need it to create a copy of the main.css and name it main_main_bk.css (don't ask - it's a convention that I need to abide by). To be clear, I need to add a _ followed by the name of the file currently being processed followed by _bk. How can I read what the name of the current file is in Gulp?
var gulp = require('gulp');
var rename = require('gulp-rename');
gulp.task('copit', function() {
gulp.src('asset/css/*.css')
.pipe(rename({suffix: '_' + ??? + '_bk'}))
.pipe(gulp.dest('asset/test'));
});
So,
asset/css/main.css -> asset/test/main_main_bk.css
asset/css/style.css -> asset/test/style_style_bk.css
Etc.

You can use basename and rename it via function
var gulp = require('gulp');
var rename = require('gulp-rename');
gulp.task('copit', function() {
gulp.src('asset/css/*.css')
.pipe(rename(function (path) {
path.basename += "_" + path.basename + "_bk";
}))
.pipe(gulp.dest('asset/test'));
});

Related

Gulp-minify how to remove duplicate files

Im trying to minify JS files with Gulp, but what is happening is that it copies all the original files im trying to minify to the destination folder /minify whereas I want there to be only the minified files with the extension -min.js.
var gulp = require('gulp');
var minify = require('gulp-minify');
var stripDebug = require('gulp-strip-debug')
var strip = require('gulp-strip-comments')
gulp.task('min-js', function() {
return gulp.src('./**/*.js', '!./node_modules', '!./*-min.js')
.pipe(minify({
ignoreFiles: ['gulpfile.js', './node_modules']
}))
.pipe(stripDebug())
.pipe(gulp.dest('./minify'))
});
gulp.task('watch', function(){
gulp.watch('lib/scripts/*.js', ['min-js']);
});
gulp.task('default', gulp.series('min-js', 'watch'));

Get a specific file from the sub directory in Node js recursively

I have a file structure like this:
lib
|->Code
|-> Style
|-> style.css
I want to get style.css file
The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with style.css.
var fs = require('fs');
var path = require('path');
var searchRecursive = function(dir, pattern) {
// This is where we store pattern matches of all files inside the directory
var results = [];
// Read contents of directory
fs.readdirSync(dir).forEach(function (dirInner) {
// Obtain absolute path
dirInner = path.resolve(dir, dirInner);
// Get stats to determine if path is a directory or a file
var stat = fs.statSync(dirInner);
// If path is a directory, scan it and combine results
if (stat.isDirectory()) {
results = results.concat(searchRecursive(dirInner, pattern));
}
// If path is a file and ends with pattern then push it onto results
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results;
};
var files = searchRecursive('./', 'style.css'); // replace dir and pattern
// as you seem fit
console.log(files); // e.g.: ['C:\\You\\Dir\\subdir1\\subdir2\\style.css']
This approach is synchronous.

How can I prefix a file name with it's parent directory using Gulp?

I am using the following hierarchy for a project:
src/img/de-de/file1.jpg, file2.gif....
src/img/en-gb/file1.jpg...
src/img/it-it/etc
There are global images inside of the img folder, and localised files in each of the mentioned sub-directories.
I am using the gulp-rename plugin to add a custom prefix (GulpTest_) to file names. However, I also want to add the sub-directory folder name to any localised files that are stored inside.
Example:
src/img/de-de/file1.jpg would be renamed GulpTest_de-de_file1.jpg
I am currently using the following code to source each of the files in the sub-directories and add the GulpTest prefix:
// Image Rename Task
gulp.src('.src/img/*/*')
.pipe(rename({prefix: "GulpTest"}))
.pipe(gulp.dest("./dst/" + )
How can I amend my task so that it it concatenates 'prefix + sub-directory + file.jpg'?
Thanks
.pipe(rename(function (path) {
console.log('path', path);
if (path.extname) {
if (path.dirname === '.') {
path.dirname = '';
}
path.basename = 'GulpTest_' + path.dirname + '_' + path.basename;
path.dirname = '';
console.log('path-new', path);
}
}))
.pipe(gulp.dest('dst/'));

Jade to HTML > index.html inside directory named after jade file

I've got a simple gulp task that compiles a .jade file to an .html file:
var gulp = require('gulp'),
jade = require('gulp-jade');
gulp.task('jade', function() {
return gulp.src('src/templates/**/*.jade')
.pipe(jade()) // pip to jade plugin
.pipe(gulp.dest('public')); // tell gulp our output folder
});
Issue
/src/templates/page.jade is compiled to HTML at the destination /public/page.html
How would I get it so it would compile /src/templates/page.jade to /public/page/index.html.
I.e. every new jade file in templates gets compiled to a an html file called index.html inside a directory with the same name as the source jade file?
Examples
/src/templates/about.jade >> /public/about/index.html
/src/templates/contact.jade >> /public/contact/index.html
/src/templates/features.jade >> /public/features/index.html
If you want to include sub-directories you can go with:
.pipe(rename(function(path){
if(path.basename != 'index')
{
var crumbs = path.dirname.split('/')
crumbs.push(path.basename)
path.basename = 'index'
path.extname = '.html'
path.dirname = crumbs.join('/')
}
return path
}))
I've been using this with success on a front-matter solution. Don't forget to include /** before /*.filetype in the gulp.src
I think what you need is gulp-rename plugin. Play around the following code, maybe it will solve your problem.
var gulp = require('gulp'),
jade = require('gulp-jade')
rename = require('gulp-rename');
gulp.task('jade', function() {
return gulp.src('src/templates/**/*.jade')
.pipe(jade())
.pipe(rename(function(path) {
var filename = path.basename;
path.basename = 'index';
path.extname = '.html';
path.dirname = filename;
return path;
}))
.pipe(gulp.dest('public'));
});
I think it's a combination of some gulp trickery and proper usage of Jade itself.
the following works for me, and results with index.html including all other files:
1) Project Structure:
- src
-- templates
--- footer.jade
--- layout.jade
-- index.jade
2) gulpfile:
var gulp = require('gulp'),
jade = require('gulp-jade');
gulp.task('jade', function() {
return gulp.src(['!src/templates/**/*.jade', 'src/index.jade'])
.pipe(jade())
.pipe(gulp.dest('public'));
});
Notice i've changed the src input. first, the source files are passed to gulp as an array. second, i've added an '!' (exclamation mark) before the files you want gulp to ignore.
3) Jade
you can (and should) use include/extend to tell jade how to assemble your page eventually.
for example, this is what my files include:
src/templates/footer.jade
h1
some text
src/templates/layout.jade
doctype html
html
head
block title
title Default title
body
block content
src/index.jade
extends ./templates/layout.jade
block title
title Article Title
block content
h1 My Article
include ./templates/footer.jade
Hope this helps. I'm just learning this too :)
I had to use gulp-rename:
var gulp = require('gulp'),
jade = require('gulp-jade')
rename = require('gulp-rename');
gulp.task('jade', function() {
return gulp.src('src/views/**/*.jade')
.pipe(jade({
pretty: true
}))
.pipe(rename(function(path){
if (path.basename=='index'){
return;
}
path.dirname=path.basename.split('-').join('/');
path.basename="index";
}))
.pipe(gulp.dest('./public/'))
callback();
});

Create Gulp tasks to minify/concat files to package sources from multiples directories into files in their respective directory

I'm writing an Angular project with the following the structure:
js/
components/
component1/
component1.directive.js
component1.controller.js
component1.factory.js
component1.rest.service.js
component2/
component2.factory.js
component2.rest.service.js
vendor/
angular/
jquery/
home.js
page2.js
where the components are shared resources and files which reside directly under js/ are packages of required components and vendor libs.
What I want to do with gulp is create a task which will stream the files from each component directory, watch for changes to trigger ngmin() and uglify(), then concat() those files into a '{componentDirectoryName}.package.min.js' file while lives in the component's directory. The result would look something like this:
js/
components/
component1/
component1.directive.js
component1.controller.js
component1.factory.js
component1.rest.service.js
component1.package.min.js
component2/
component2.factory.js
component2.rest.service.js
component2.package.min.js
Current implementation:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ camelize: true});
var glob = require('glob');
var StreamQueue = require('streamqueue');
var publicDir = './src/main/webapp/public/';
var jsDir = publicDir + 'js/';
var components = jsDir + 'components/';
gulp.task('js', function() {
var componentsDirectories = glob.sync(components + '/*/');
var queue = new StreamQueue();
componentsDirectories.forEach(function(directory) {
var componentName = directory.match(/.+\/(.+)\/$/)[1];
queue.queue(
gulp.src([directory + '*.js', '!' + directory + '*-package.min.js'])
.pipe($.ngmin())
.pipe($.jsmin())
.pipe($.concat(componentName + "-package.min.js"))
.pipe(gulp.dest(directory))
);
});
return queue.done().pipe($.livereload());
});
gulp.task('watch', function() {
gulp.watch([components + '**/*.js', '!' + components + '**/*.min.js'], ['js']);
});
gulp.task('default', ['js', 'watch']);
You can use node-glob to get your components' names.
To register multiple sources as a single task you can compose streams with streamqueue.
Here's my solution:
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var ngmin = require('gulp-ngmin');
var livereload = require('gulp-livereload');
var glob = require('glob');
var StreamQueue = require('streamqueue');
gulp.task('js', function() {
var componentsFolders = glob.sync('components/*/');
var queue = new StreamQueue();
componentsFolders.forEach(function(folder){
var componentName = folder.match(/.+\/(.+)\/$/)[1];
queue.queue(
gulp.src([folder + '*.js', '!' + folder + '*.package.min.js'])
.pipe(ngmin())
.pipe(uglify())
.pipe(concat(componentName + ".package.min.js"))
.pipe(gulp.dest(folder))
);
});
return queue.pipe(livereload());
});
gulp.task('default', ['js']);

Categories

Resources