Coder Social home page Coder Social logo

nickjj / esbuild-copy-static-files Goto Github PK

View Code? Open in Web Editor NEW
34.0 2.0 5.0 41 KB

An esbuild plugin to copy static files that changed from a source directory to a destination directory.

License: MIT License

JavaScript 46.75% Shell 53.25%
esbuild esbuild-plugin copy static-files

esbuild-copy-static-files's Introduction

esbuild-copy-static-files

CI

An esbuild plugin to efficiently copy static files from a source directory to a destination directory.

✔️ Only copy files that changed (it compares an MD5 hash of each src and dest file)
✔️ No 3rd party dependencies (it only uses a few functions from Node's standard library)

Demo Video

This video mostly covers what's in this README along with a bit more detail around the "why".

Demo Video

Why?

So you've decided that you want to copy HTML, icons, images, fonts and other static files from a source directory to a destination directory through esbuild. Great, I do too.

Blindly recursively copying a src to dest directory can be both inefficient and distracting. For example if you have 50 static files and update a single JS file then you'll end up copying all 50 static files over.

That's creating a lot of unnecessary disk writes. Depending on which web framework you use, that might cause a lot of log spam in development too. That could be due to live reload picking up a bunch of files that technically changed.

This plugin fixes the above because it'll only copy static files if they changed on disk since they were last copied. You can think of this plugin as being similar to using rsync instead of cp on the command line except there's no extra watcher or command that you need to run. It's all seamlessly integrated into esbuild.

How it works at a high level

For most web apps, when it comes to my front-end I like the idea of this type of directory structure:

# This is where your assets are located and is used as input for esbuild.
assets/
├── css/
│   └── app.css
├── js/
│   └── app.js
├── static/
│   ├── images/
│   │   └── logo.png
│   ├── favicon.ico
│   ├── robots.txt
├── esbuild.config.js
├── package.json
├── postcss.config.js
├── tailwind.config.js
└── yarn.lock

# This is the output of where esbuild will write its file(s) to.
public/
├── css/
│   └── app.css
├── js/
│   └── app.js
├── images/
│   └── logo.png
├── favicon.ico
├── robots.txt

In my opinion it's really nice having all of your assets in 1 spot which then get output to another location.

esbuild manages the js/ directory and TailwindCSS (or whatever you prefer) manages the css/ directory but that leaves us with a bunch of static files that are composed of HTML, icons, images, fonts and more.

This esbuild plugin will copy your static files to your esbuild output directory. No processing will be done on these static files. It's a quick cp and only files that have changed are copied so it's really efficient.

You can name your static/ and public/ directories and configure their paths however you want. We'll go over all of the configuration options in a bit.

Installation

Just a heads up, this package uses Node's fs.cpSync function which depends on using at least Node v16.7.

# Prefer Yarn?
yarn add --dev esbuild-copy-static-files

# Or NPM instead?
npm install --save-dev esbuild-copy-static-files

You can check it out on: https://www.npmjs.com/package/esbuild-copy-static-files

Getting Started

If you had the same directory structure as above, here's the bare minimum esbuild config to get going:

const esbuild = require('esbuild')
const copyStaticFiles = require('esbuild-copy-static-files')

esbuild.build({
  entryPoints: ['./js/app.js'],
  outfile: '../public/js/app.js',
  bundle: true,
  minify: true,
  sourcemap: false,
  watch: false,
  plugins: [copyStaticFiles()],
})

Configuration

This plugin uses Node's fs.cpSync function under the hood. Any option that it has can be configured here.

Here's a list of what you can configure and the default values if you don't override them:

  plugins: [
    copyStaticFiles({
      src: './static',
      dest: '../public',
      dereference: true,
      errorOnExist: false,
      filter: EXPLAINED_IN_MORE_DETAIL_BELOW,
      preserveTimestamps: true,
      recursive: true,
    })
  ],

In most cases you'll likely only change the src and dest to fit your project's directory structure.

Here's the docs of every configurable option from Node's documentation:

  • src source path to copy.
  • dest destination path to copy to.
  • dereference dereference symlinks.
  • errorOnExist when force is false and the destination exists, throw an error.
  • filter function to filter copied files / directories. Return true to copy the item, false to ignore it.
  • force overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior.
  • preserveTimestamps when true timestamps from src will be preserved.
  • recursive copy directories recursively.

How does the filter function work?

By default it will filter out, AKA skip copying any files that haven't changed. It does this by getting the MD5 hash of each src and dest file. If both files have the same MD5 hash then it gets skipped.

This is nice because if you had let's say 50 static files and only 1 of them changed then only 1 file will get copied.

Using a custom filter function

If you can think of a more efficient way of detecting which file(s) should get copied you can customize the filter function by providing your own function that returns true or false based on whatever criteria you prefer.

Here's an example of a simple filter function that always returns true:

  plugins: [
    copyStaticFiles({
      filter: function () { return true },
    })
  ],

About the author

I'm a self taught developer and have been freelancing for the last ~20 years. You can read about everything I've learned along the way on my site at https://nickjanetakis.com.

There's hundreds of blog posts / videos and a couple of video courses on web development and deployment topics. I also have a podcast where I talk with folks about running web apps in production.

esbuild-copy-static-files's People

Contributors

nickjj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

esbuild-copy-static-files's Issues

Exclude certain files from being copied

I've been using this plugin for a month now to simplify publishing static files into the resulting build and I'm pleased with it so far. Due to some quirks in the project I'm working on, I need to exclude certain files from being copied.

While I know I can override the filter function as an optional argument, it would require me to re-implement the entire logic of filter function which seems a bit excessive.

I can spin up a PR to add this functionality but I'm looking for guidance for the best way to implement this...

My thoughts are I could take one of the following approaches:

  1. Add a new exclude argument to the options object and have the built-in filter function evaluate that when it's called (e.g. if source file name with leading directory stripped matches an element in the excluded array, then return false).

  2. Export the filter function to allow it to be reused externally, then one doesn't have to choose between your filter logic and their filter logic.

The problem I see with option 1 is this would make the API and documentation a bit clunky since it requires a caveat in giant bold letters that exclude will be ignored if the filter function is overridden.

Whether option 2 is palatable is up to you and your preferences.

What are your thoughts?

fs.cpSync not found in Node 16.3.0

fs.cpSync is an experimental API that should not be used in production.
Maybe it should be changed to some stable API until it gets fixed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.