Use esbuild instead of uglifyjs-folder and csso-cli

You can use the superfast esbuild instead of uglifyjs-folder and csso-cli to copy (and minify) your JavaScript and/or CSS files (without having to bundle the files) in your npm scripts.

Why would you want to do this:

  • simplify your build process
  • reduce number of dependencies (and potential supply chain attack vectors)
  • outdated dependencies

Note: esbuild is not really meant to just copy files without bundling, so use the following with care.

Copy a folder with esbuild

If you just want to copy the contents of a folder, you have do do so by file type:

# copy js files without any modification
esbuild ./somefolder/*.js --loader:.js=copy --outdir=somefolder

# copy with minification
esbuild ./somefolder/*.js --bundle --minify --sourcemap --external:*.js --format=esm --outdir=somefolder

The trick to copy with minification but “without” bundling is to actually bundle --bundle --minify --sourcemap, but mark all files in the folder you want to copy as external --external:./somefolder/*. This way the imports are not inlined but kept as import statements. The contents of the files is rewritten though (let, const –> var).

Use esbuild instead of csso-cli

The same as above works for CSS files instead:

# copy css files without any modification
esbuild ./somefolder/*.css --loader:.css=copy --outdir=somefolder

# copy with minification
esbuild ./somefolder/*.css --bundle --sourcemap --external:*.css --outdir=test

If you get an error such as No loader is configured for ".woff2" files: somefolder/somefont.woff2 just add the argument --external:*.woff2

Happy “building”.

Leave a comment

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