How to make gulp-rename rename a concrete single file? - javascript

I generate CSS from LESS files and want to give to all generated Bootstrap CSS files a prefix "bootsrtap", but not to the bootstrap.css. So, I set the prefix directly after the compilation, but all my attempts to do a futher rename are failing.
var gulp = require('gulp'),
less = require('gulp-less'),
watch = require('gulp-watch'),
prefix = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
filter = require('gulp-filter'),
rename = require('gulp-rename'),
path = require('path')
;
// ...
gulp.task('build-vendors', function() {
gulp.src(['./public/components/bootstrap/less/theme.less', './public/components/bootstrap/less/bootstrap.less']) // path to less file
.pipe(plumber())
.pipe(less())
.pipe(rename({prefix: 'bootstrap-'}))
.pipe(gulp.dest('./public/css')) // path to css directory
;
});
gulp.task('clean-up', function() {
// const bootstrapFileRenameFilter = filter(['*', 'bootstrap-bootstrap.css']);
gulp.src('./public/css/bootstrap-bootstrap.css')
.pipe(plumber())
// .pipe(bootstrapFileRenameFilter)
.pipe(rename({basename: 'bootstrap.css'}))
.pipe(gulp.dest('./public/css'))
;
});
gulp.task('watch', function() {
gulp.watch('public/less/*.less', ['build-less', 'build-vendors'])
});
// gulp.task('default', ['watch', 'build-less', 'build-vendors']);
gulp.task('default', ['build-less', 'build-vendors', 'clean-up']);
What I expect:
./public/css/bootstrap-theme.css
./public/css/bootstrap.css
What I'm currently getting:
./public/css/bootstrap-theme.css
./public/css/bootstrap-bootstrap.css
How to rename a single file from a.foo to b.bar?

gulp-rename accepts a function as an argument to do the renaming. This allows you to target specific files for renaming using any criteria you like. In your case:
gulp.task('build-vendors', function() {
gulp.src(['./public/components/bootstrap/less/theme.less',
'./public/components/bootstrap/less/bootstrap.less'])
.pipe(plumber())
.pipe(less())
.pipe(rename(function(path) {
//rename all files except 'bootstrap.css'
if (path.basename + path.extname !== 'bootstrap.css') {
path.basename = 'bootstrap-' + path.basename;
}
}))
.pipe(gulp.dest('./public/css'));
});
Since you now only rename those files where you actually want to have the bootstrap- prefix, you don't have to clean-up your mess afterwards and can just drop the whole clean task altogether.

Related

gulp. moving files in neighbors dir

The simplified structure of the project looks like this. JavaScript files that lie in the es6 directory must be moved to the neighbors directory js.
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task('build-js', function () {
gulp.src('app/core/**/es6/**/*.js')
.pipe(babel({
presets: ["env"]
}))
.pipe(gulp.dest(???)); // need move to ../js
});
Please, help me, how to implement this in gulp?
I assume that the babel pipe doesn't move the js files that are in the es6 folder or add any folders. And that your gulpfile.js is at the root level of your "app" folder.
var gulp = require('gulp');
var path = require('path');
var rename = require('gulp-rename');
gulp.task('default', function () {
// with gulpfile.js at root of "app" folder
return gulp.src('core/**/es6/*.js')
.pipe(rename(function (file) {
console.log("file.dirname = " + file.dirname);
// file.dirname = AdminTools\es6
// file.dirname = Permissions\es6
// strip off the last folder 'es6'
var temp = file.dirname.split(path.sep)[0];
file.dirname = temp + "/js";
// file.dirname = AdminTools\js
// file.dirname = Permissions\js
}))
.pipe(gulp.dest('core'));
});

Gulp 4.0: gulp-remember or gulp-cache prevent sass to compile properly (Incremental build)

yesterday I've upgraded my Gulp to 4.0 in order to gain some speed while compiling styles for my project (they got big, right now on my Mac Pro 2016 I need to wait 19seconds)
After some digging I decided to add gulp-cached and gulp-remember to my build.
Here's my current gulpfile.js for the styles:
var gulp = require('gulp'),
sass = require('gulp-sass'),
cached = require('gulp-cached'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer'),
remember = require('gulp-remember'),
gs = gulp.series,
concat = require('gulp-concat'),
gp = gulp.parallel;
gulp.task('compile:styles', () => {
return gulp.src([
// Grab your custom scripts
'./assets/scss/**/*.scss'
])
.pipe(sourcemaps.init()) // Start Sourcemaps
.pipe(cached('sass'))
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(remember('sass'))
.pipe(sourcemaps.write('.')) // Creates sourcemaps for minified styles
.pipe(gulp.dest('./assets/css/'));
});
gulp.task('watch:styles', () => {
gulp.watch('./assets/scss/**/*.scss', gs('styles'))
.on('change', function (event) {
console.log("event happened:"+JSON.stringify(event));
if (event.type === 'deleted') {
//delete from gulp-remember cache
remember.forget('sass', event.path);
//delete from gulp-cached cache
delete cache.caches['sass'][event.path];
}
});
});
gulp.task('watch', gp(
'watch:styles'
));
My issue here is that my build works well on first compilation which takes about 3 seconds, later on where ever I do a change it can see in which file I made that change, and it starting to compile, but the output file does not have the changes inside.
I think I am not getting something when it comes to gulp-cached and gulp-remeber. But at the end of the file you can see a function that are supposed to clean the caches once a change was made.
Can you please take a look at my code? Maybe you will have some advice.
Cheers!
### EDIT 26.08
I have encountered the following post while looking for a solution:
http://blog.reactandbethankful.com/posts/2015/05/01/building-with-gulp-4-part-4-incremental-builds/
I went with it accordingly with the following code (but the effect is same as in above example):
// Grab our gulp packages
var gulp = require('gulp'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer'),
gs = gulp.series,
gp = gulp.parallel,
cache = require('gulp-memory-cache');
gulp.task('compile:styles', () => {
return gulp.src('./assets/scss/**/*.scss', {since: cache.lastMtime('sass')})
.pipe(sourcemaps.init()) // Start Sourcemaps
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(cache('sass'))
.pipe(sourcemaps.write('.')) // Creates sourcemaps for minified styles
.pipe(gulp.dest('./assets/css/'));
});
gulp.task('watch:styles', () => {
gulp.watch('./assets/scss/**/*.scss', gs('compile:styles'))
.on('change', cache.update('sass'));
});
gulp.task('build', gs(
'compile:styles',
'watch:styles'
));
I have created a complete gulpfile.js here:
https://gist.github.com/MkBeeCtrl/5a6a0900dba1c5d42dc7b6da211b3e95
With js files compilation included.
// Grab our gulp packages
var gulp = require('gulp'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer'),
gs = gulp.series,
gp = gulp.parallel,
cached = require('gulp-cached'),
dependents = require('gulp-dependents');
gulp.task('compile:styles', () => {
return gulp.src('./assets/scss/**/*.scss')
.pipe(cached('sass'))
.pipe(dependents())
.pipe(sourcemaps.init()) // Start Sourcemaps
.pipe(sass())
.pipe(autoprefixer({browsers: ['last 2 versions']}))
.pipe(sourcemaps.write('.')) // Creates sourcemaps for minified styles
.pipe(gulp.dest('./assets/css/'));
});
gulp.task('watch:styles', () => {
gulp.watch('./assets/scss/**/*.scss', gs('compile:styles'))
.on('change', function (event) {
console.log("event happened:"+JSON.stringify(event));
if (event.type === 'deleted') {
//delete from gulp-remember cache
//emember.forget('sass', event.path);
//delete from gulp-cached cache
delete cache.caches['sass'][event.path];
}
});
});
gulp.task('build', gs(
'compile:styles',
'watch:styles'
));
The above solution works the way I want, so if you want to produce separate CSS files from multiple imported files, you can go with it. It's not blazing fast solution but I have managed to save about 1 second when recompiling (already saved about 15s, when I started this topic, a build lasted 19 secs):
1st compile: ~3.5s
2nd or late: ~2.4s
You dont need to concate or order here as the whole order thing happens when you import scss files into you main file.
Try this one. I suppose it might do what you want to achieve:
'use strict';
const gulp = require('gulp');
const path = require('path');
const cached = require('gulp-cached');
const remember = require('gulp-remember');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
gulp.task('styles:compile', function() {
return gulp.src('assets/scss/**/*.scss', {since: gulp.lastrun('styles:compile')})
.pipe(sourcemaps.init())
//.pipe(cached('sass')) - a smarter but heavier alternative to since
.pipe(remember('sass'))
.pipe(concat('all.sass'))
.pipe(sass())
.pipe(autoprefixer({ browsers: ['last 2 versions'] }))
.pipe(sourcemaps.write())
.pipe(gulp.dest('assets/css/'));
});
gulp.task('styles:watch', function() {
var watcher = gulp.watch('assets/scss/**/*.scss', gulp.series('compile:styles'));
watcher.on('unlink', function(filepath) {
remember.forget('sass', path.resolve(filepath));
//delete cached.caches.sass[path.resolve(filepath)];
});
});
gulp.task('default', gulp.series('styles:compile', 'styles:watch'));
Install path plugin to resolve paths. Use 'unlink' event if you want to detect when a file gets deleted. since just checks dates which is faster compared to cached that reads and compares content. But cached is more reliable (for example, when you deleted and then returned the file using your IDE tools since will not work since the file will be returned again with its old date). Also check paths - I might have messed them up.

Gulp watch() not triggering the less process

The following gulp watch task isn't getting triggered when I change any LESS file in the project. Can anyone spot what I'm doing wrong? Most the answers here say to NOT use the watch-less module, which I'm not. It's supposed to listen to changes in any LESS file in the project and when one changes, go to the app.less file to regenerate the CSS file (app.less has #includes to all the files).
var watch = require("gulp-watch");
var less = require("gulp-less");
gulp.watch(paths.source + "**/*.less", function(event){
gulp.src(paths.source + paths.assets + paths.less + "app.less")
.pipe(less().on("error", console.log))
.pipe(gulp.dest(paths.dev + paths.css));
});
Here are some issues:
require("gulp-watch"); is useless here. Actually gulp.watch is a core API of gulp.
The gulpfile.js consists of several gulp tasks.
Run gulp watch in your terminal.
For example:
var gulp = require('gulp');
var path = require('path');
var less = require('gulp-less');
var paths = {
// your paths
};
gulp.task('styles', function () {
return gulp.src(paths.source + paths.assets + paths.less + "app.less")
.pipe(less({
// paths to be used for #import directives
paths: [ path.join(__dirname, 'less', 'includes') ]
}))
.pipe(gulp.dest('./'));
});
gulp.task('watch', function() {
gulp.watch('less/**/*.less', ['styles']);
});

gulp - exclude a file when minifying CSS

Im new to Gulp.. I have been able to successfully install and concatenate and minify my .js and .css files, however, there is one .css file which i want to exclude - print.css
Ive followed the instructions here: https://www.npmjs.org/package/gulp-ignore install gulp-ignore in my local directory, and modified my gulpfile.js to:
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var minifyCSS = require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var exclude = require('gulp-ignore').exclude;
var paths = {
scriptsNonAuth: ['Non-Auth/javascript/*.js'],
scriptsAuth: ['Auth/javascript/*.js'],
stylesNonAuth: ['Non-Auth/css/*.css'],
stylesAuth: ['Auth/css/*.css'],
};
// CSS Task - Non Authenticated
gulp.task('minify-css-non-auth', function() {
gulp.src(paths.stylesNonAuth)
.pipe(minifyCSS(opts))
.pipe(concat('all.min.css'))
.pipe(gulp.dest('Non-Auth/css'))
});
// CSS Task - Authenticated
gulp.task('minify-css-auth', function() {
gulp.src(paths.stylesAuth)
.pipe(minifyCSS(opts))
**.pipe(exclude('Auth/css/print.css'))**
.pipe(concat('all.min.css'))
.pipe(gulp.dest('Auth/css'))
});
Within my CSS Task - Secure, i have included .pipe(exclude('Secure/css/print.css'))
When i run gulp minify-css-secure, the task completes but upon inspecting the new all.min.css, i cant see the contents of print.css within there too.
It's unclear what you are trying to achieve. If I get it right, you want to:
minify all css files (including print.css)
concat all files except print.css into all.min.css
put minified all.min.css and print.css into destination folder
To achieve that, you can use StreamQueue. (source)
var streamqueue = require('streamqueue');
var paths = {
scriptsNonAuth: ['Non-Auth/javascript/*.js'],
scriptsAuth: ['Auth/javascript/*.js'],
stylesNonAuth: ['Non-Auth/css/*.css'],
stylesAuth: ['Auth/css/*.css', '!Auth/css/print.css'],
};
gulp.task('minify-css-auth', function() {
return streamqueue({ objectMode: true },
gulp.src(paths.stylesAuth)
.pipe(minifyCSS(opts))
.pipe(concat('all.min.css')),
gulp.src('Auth/css/print.css'))
.pipe(minifyCSS(opts))
)
.pipe(gulp.dest('Auth/css'))
});
If you want to just exclude some files, you don't need gulp-ignore. Gulp supports ignore globs.
Just prefix the path to exclude with bang.
Like this:
stylesAuth: ['Auth/css/*.css', '!Auth/css/print.css']

gulp.js strips relative paths of output files [duplicate]

This question already has an answer here:
Why does gulp.src not like being passed an array of complete paths to files?
(1 answer)
Closed 7 years ago.
I have a gulp.js configuration set up to automatically compile my SASS and CoffeeScript on save. It works, except that the relative paths are totally lost, and all the files are output into a single flat directory. I would like to retain the sub-directory structure of my app/assets/sass and app/assets/coffee directories when the final CSS and JS files are compiled. Here is my gulpfile:
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
var minifycss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-ruby-sass');
var coffee = require('gulp-coffee');
var sassDir = 'app/assets/sass';
var coffeeDir = 'app/assets/coffee';
gulp.task('sass', function() {
return gulp.src(sassDir + '/**/*.scss')
.pipe(plumber())
.pipe(sass({ style: 'compress' }).on('error', gutil.log))
.pipe(autoprefixer('last 10 versions'))
.pipe(minifycss())
.pipe(gulp.dest('public/css'));
});
gulp.task('coffee', function() {
return gulp.src(coffeeDir + '/**/*.coffee')
.pipe(plumber())
.pipe(coffee({ bare: true }).on('error', gutil.log))
.pipe(gulp.dest('public/js/coffee)'));
});
gulp.task('watch', function() {
gulp.watch(sassDir + '/**/*.scss', ['sass']);
gulp.watch(coffeeDir + '/**/*.coffee', ['coffee']);
});
gulp.task('default', ['sass', 'coffee', 'watch']);
only split path string with / and get the last which is the filename and extension and then cut it
to get files path
gulp.task('testing', function() {
var orginalFile="tt/ee/style.scss";
var pathArray=orginalFile.split('/');
var destination=orginalFile.replace(pathArray[pathArray.length-1],"")
gulp.src(orginalFile)
.pipe(sass())
.pipe(gulp.dest(destination));
})
});

Categories

Resources