Here’s an example of a gulpfile.js
that contains a simple task that minifies a JavaScript file:
const gulp = require('gulp');
const uglify = require('gulp-uglify');
gulp.task('minify', function() {
return gulp.src('src/main.js')
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
In this example, the gulp.task
method is used to define a task called “minify”. The task uses the gulp.src
method to specify the source file, src/main.js
, which is then piped through the uglify
plugin, which minifies the JavaScript code. The minified code is then piped to the gulp.dest
method, which specifies the destination directory, dist
, where the minified file will be saved.
You can run this task from the command line by typing gulp minify
.
Here’s another example, this time using multiple tasks in a gulpfile.js:
const gulp = require('gulp');
const sass = require('gulp-sass');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
// Compile Sass files
gulp.task('sass', function() {
return gulp.src('src/sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'));
});
// Minify and concatenate JavaScript files
gulp.task('scripts', function() {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(gulp.dest('dist/js'));
});
// Run multiple tasks in parallel
gulp.task('build', gulp.parallel('sass', 'scripts'));
This gulpfile.js defines two tasks: sass
and scripts
. The sass
task compiles Sass files and saves the generated CSS files in the dist/css
directory. The scripts
task minifies and concatenates JavaScript files and saves the result in the dist/js
directory. The gulp.parallel
method is used to run the sass
and scripts
tasks in parallel, and finally, the build
task is defined to run both of them at once.
You can run this task from the command line by typing gulp build
.
This is just a simple example, you can use a lot more plugins and create more complex tasks with gulp. It’s a very powerful tool that can help you streamline your development workflow and automate repetitive tasks.