Introduction to Gulp Rename
Gulp-rename is a popular plugin for the Gulp JavaScript task runner that simplifies file renaming. It’s a critical tool for automation in web development, allowing developers to dynamically change file names and extensions.
Installation
First, you need to install the gulp-rename plugin using npm:
npm install --save-dev gulp-rename
Basic Usage
Below is a basic example demonstrating how to use gulp-rename:
const gulp = require('gulp'); const rename = require('gulp-rename');
gulp.task('rename', function() {
return gulp.src('src/*.js')
.pipe(rename('renamed.js'))
.pipe(gulp.dest('dist'));
});
Advanced Renaming Techniques
Gulp-rename provides a variety of options to handle complex renaming needs:
Changing Extensions
You can change file extensions easily:
const rename = require('gulp-rename');
gulp.task('change-ext', function() {
return gulp.src('src/*.html')
.pipe(rename({ extname: '.php' }))
.pipe(gulp.dest('dist'));
});
Renaming with a Function
You can rename files dynamically using a function:
const rename = require('gulp-rename');
gulp.task('dynamic-rename', function() {
return gulp.src('src/*.css')
.pipe(rename(function(path) {
path.basename += '-renamed';
path.extname = '.min.css';
}))
.pipe(gulp.dest('dist'));
});
Using Templates
Gulp-rename supports templates for renaming:
const rename = require('gulp-rename');
gulp.task('template-rename', function() {
return gulp.src('src/*.txt')
.pipe(rename({
dirname: 'new_dir',
basename: 'new_base',
prefix: 'prefix-',
suffix: '-suffix',
}))
.pipe(gulp.dest('dist'));
});
App Example
Let’s look at an example app that uses multiple gulp-rename APIs:
const gulp = require('gulp'); const rename = require('gulp-rename');
gulp.task('rename-all', function() {
return gulp.src('src/**/*')
.pipe(rename(function(path) {
path.dirname += "/new";
path.basename += "-new";
path.extname = ".new";
}))
.pipe(gulp.dest('dist'));
});
gulp.task('default', gulp.series('rename-all'));
In the above example, the task ‘rename-all’ applies multiple renaming rules to all files in the ‘src’ directory and saves them in the ‘dist’ directory.
By leveraging gulp-rename, developers can effectively manage and organize their files within projects, contributing to more maintainable and scalable codebases.
Hash: 58d0e563bab671d88a9ff05623505cff49e44a7e3f15aec263658184339d080d