gulp
is a lightweight automation build tool that helps us automatically run many tedious and repetitive tasks, such as code minification, concatenation, and so on, saving us a lot of time. While creating my resume, I needed to use less
, which requires compilation, so I took the opportunity to learn this tool.
Installing Gulp.js
Since gulp
is built on node
, you must first install node
. After node
is installed, you can install gulp
using npm
:
npm install -g gulp
Configuration in the Project
Since I needed to compile less
, I first had to install the gulp-less
plugin:
npm install --save-dev gulp gulp-less
The --save-dev
flag in the command adds the installed package to your package.json
configuration file:
"dependencies": {
"gulp": "^3.8.10",
"gulp-livereload": "^3.4.0",
"gulp-less": "^2.0.1",
"less-plugin-autoprefix": "^1.3.0"
},
If your project doesn’t have this file, you can create it using the npm init
command.
Create a Gulpfile.js
file in the root directory of your project. This file is used to define which plugins are used, which tasks to run, and so on.
While creating my resume, I needed to copy two dependency libraries managed by bower
into a specific folder, and also monitor and compile less
files. Therefore, the configuration file is as follows:
var gulp = require("gulp"),
less = require("gulp-less"); //引入less插件
// 定义 less 任务
gulp.task("less", function () {
gulp.src("./less/main.less").pipe(less()).pipe(gulp.dest("./style"));
});
//复制文件到特定目录
gulp.task("depends", function () {
gulp
.src([
"./bower_components/pagepiling.js/jquery.pagepiling.min.js",
"./bower_components/pagepiling.js/jquery.pagepiling.css",
])
.pipe(gulp.dest("./depends"));
});
//监控less文件,一旦有更改,就执行less编译任务
gulp.task("watch", function () {
gulp.watch("less/*.less", ["less"]);
});
//默认任务
gulp.task("default", ["less", "depends", "watch"]);
Here’s a breakdown:
gulp.task()
: This function defines a task. It requires two arguments: the task name and a callback function.gulp.src()
: This function is used to specify the source files, taking the path to the files that need to be processed..pipe()
: This passes the input files to a processing function. For example,.pipe(less())
passes the files fromgulp.src('./less/main.less')
to theless()
function.gulp.dest()
: This output function writes files to a specified directory.gulp.watch()
: This monitoring function executes a corresponding function whenever changes are detected in the specified files.
This article was published on January 18, 2015 and last updated on January 18, 2015, 3913 days ago. The content may be outdated.