There are two many focuses when building an efficient development workflow:
- It needs to produce a well optimised and efficient to run website
- It needs to make it quicker and easier for the developer to work
This post is about the second of these things. More specifically, how we can save time by getting Gulp to perform the FTP actions for us, not only building the website but also deploying it for us.
To start we need to install the vinyl-ftp plugin using NPM…
npm install --save-dev vinyl-ftp
Then (if you’re not automatically requiring plugins) you need to require it at the top of your “gulpfile.js” file…
var vftp = require("vinyl-ftp");
We then want to add a new task to handle the FTP…
var ftp = function() {
var conn = vftp.create({
host: "yourhost.com",
user: "[email protected]",
pass: "a-R3a1!y-G0oD-pa$$w0rd",
parallel: 1,
log: util.log
});
return gulp.src(["build/**"],{base:"build",dot:true})
.pipe(conn.newer("/"))
.pipe(conn.dest("/"));
};
As you may have noticed, I like short but descriptive task names, so “ftp” works quite well for me. Firstly we need to specify the connection details – personally I prefer to stick to a single thread (parallel = 1) but you can increase this if you want to speed things up and your FTP server doesn’t mind.
Let’s briefly talk about those src() parameters…
- The array is the files that want to be uploaded – I want upload all files in all subdirectories of my “build” folder, so “build/**” covers this.
- The object contains options of which there are a few available, but I tend to use:
- base – effectively this removes “build” from the path when it uploads, as I want the files to go straight into the root “public_html” folder
- dot – this means that “build/**” will also match with dot files, such as .htaccess – by default it won’t and therefore this file won’t be uploaded
I also call newer() to ensure that I only upload files that have been modified since they were last uploaded, which reduces unnecessary file uploads, but calling dest() to trigger the upload.
I then like to have two separate exported methods, one for build and one for deploy…
exports.default = gulp.series(gulp.parallel(php,js,img,css),final);
exports.deploy = gulp.series(gulp.parallel(php,js,img,css),final,ftp);
This means that if I just call “gulp” from the command line then the “default” will run and just perform a build, but if I call “gulp deploy” then the project will be both built and deployed via FTP.