Use the `copyfiles` command in front-end development to manage file copying

As front-end developers, we often need to copy various static resource files during the build process.
I’d like to share a highly practical tool — copyfiles, which makes file copying simple and efficient.

What is copyfiles?

copyfiles is a Node.js command-line tool specifically designed for copying files and directories. Its primary purpose is to streamline the copying of static resources in front-end project builds.

Installation

1
2
3
4
5
# Global installation
npm install -g copyfiles

# Or install as a dev dependency in your project
npm install --save-dev copyfiles

Basic Usage

The simplest way to use it is by specifying the source files and target directory:

1
copyfiles src/assets/*.png dist/images

This will copy all PNG files from the src/assets directory to the dist/images directory.

Common Options

copyfiles provides several useful options:

  1. -u, --up <n> - Remove n levels of directories from the source path

    1
    2
    copyfiles -u 1 src/assets/**/*.png dist
    # This preserves the structure under assets but excludes the src directory
  2. -f, --flat - Flatten the directory structure

    1
    2
    copyfiles --flat src/assets/**/*.{jpg,png} dist/images
    # All files will be copied directly to the target directory, ignoring the original structure
  3. -e, --exclude - Exclude specific files

    1
    copyfiles -e "**/*.temp.*" src/**/* dist

Configuration in package.json

Integrating copyfiles into npm scripts is very convenient:

1
2
3
4
5
6
{
"scripts": {
"copy-assets": "copyfiles -u 1 src/assets/**/*.* dist",
"build": "webpack && npm run copy-assets"
}
}

Real-World Use Case

In my latest project, I needed to copy various types of resource files to different target directories:

1
2
3
4
5
6
7
8
9
{
"scripts": {
"copy:images": "copyfiles -u 2 src/assets/images/**/*.* dist/images",
"copy:fonts": "copyfiles -u 2 src/assets/fonts/**/*.* dist/fonts",
"copy:config": "copyfiles -f src/config/*.json dist/config",
"copy:all": "npm run copy:images && npm run copy:fonts && npm run copy:config",
"build": "webpack && npm run copy:all"
}
}

With this setup, running npm run build will first compile the code with webpack and then automatically copy all necessary resource files to their respective target directories.


Use the `copyfiles` command in front-end development to manage file copying
https://www.hardyhu.cn/2024/12/22/Use-the-copyfiles-command-in-front-end-development-to-manage-file-copying/
Author
John Doe
Posted on
December 22, 2024
Licensed under