Skip to content

How to: rename a certain files

Đăng Tú edited this page Jul 20, 2019 · 1 revision

The case

Mr.Sensitive has 3 root scss files (modA.scss, modB.scss, style.scss). He want to rename 2 files after compiled into (A.css and B.css). What should he do? Below is his gulp task:

const { task, src, dest } = require('gulp');
const rename = require('gulp-rename');
const sass = require('gulp-sass');

const scss = './scss/**/*.scss';
task('sass', () => {
	return src(scss)
		.pipe(sass().on('error', sass.logError))
		.pipe(rename('A.css')) // This is not going to work, and Mr.Sensitive knew it.
		.pipe(dest('./public'));
});

Solution

After awhile, a nice hermit pass by seeing him cry bitterly on the sidewalk. Feeling annoying, the hermit decided to help him so that the hermit will no longer have to hear his sorrow cry. This is the hermit solution:

task('sass', () => {
	return src(scss)
		.pipe(sass().on('error', sass.logError))
		.pipe(rename(path => {
			switch (path.basename) {
				case 'modA': path.basename = 'A'; break; // rename to A.css
				case 'modB': path.basename = 'B'; break; // rename to B.css
				default: // Not rename
			}
		}))
		.pipe(dest('./public'));
});

The hermit decides to pass the param path through switch case to filter the name needed to be changed. Thou names need no change shall pass to default and stay the same as they were.

Clone this wiki locally