How to Safely Copy Files with Gulp 5

Last year, I updated the build tool for this blog’s theme. I upgraded from Gulp version 4 to version 5. After I finished, I worked as usual thinking nothing of it.

That was until, out of the blue, after uploading a zipped copy of the theme to my remote WordPress server, my font files were mangled or missing. Images also wouldn’t load at all, but the paths were correct.

After some digging around, I discovered that while copying and zipping files, Gulp 5 was sending corrupted image and font files to the final copy.

In short, Gulp 5 copies files from src to dest as utf-8 files, while images and fonts need to be copied as binaries. Basically, this GitHub issue describes everything.

Indeed, what we will do here is the same as described in the GitHub issue.

Fixing Images and Fonts

To fix the copying process, here are some code snippets from this theme’s gulp file.

…
function copyFontsFolder() {
  return src("./custom-fonts/**/*", { encoding: false }).pipe(
    dest("./dist/custom-fonts"),
  );
}

function copyImagesFolder() {
  return src(
    ["./images/*.gif", "./images/*.jpg", "./images/*.png", "./images/*.svg"],
    { encoding: false },
  ).pipe(dest("./dist/images"));
}
…
exports.copyFiles = series(
  …
  copyFontsFolder,
  copyImagesFolder,
  …
);

Adding encoding: false removes the utf-8 encoding and leaves the original file’s encoding unchanged.

For Zipped Files

We must also set the encoding to false for files that gulp-zip zips up.

function zipUp() {
  return src("./dist/**/*", { encoding: false })
    .pipe(zip("jasong-designs-2.zip"))
    .pipe(dest("./dist"));
}

Conclusion

I’ve been burned by this issue twice. I had to re-upload the non-corrupted files from my local theme to the remote using FileZilla. Thus, I am now using a new method for copying files with just some npm scripts. I may explore the new method in a future post.

However, if you want to keep everything with Gulp 5 as your single build tool, you will need to add the above argument to any images or fonts you are copying over.

Thanks for reading.

Featured image by Clker-Free-Vector-Images from Pixabay


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.