A simple PHP script to combine and minify multiple JS or CSS files passed via URI, inspired by jsDelivr.
It was created for when you have multiple scripts at a static/CDN domain, allowing you to pick and bundle different libraries based on your current needs.
Generally, it is best to combine multiple assets into bundles using a task runner such as webpack or Gulp, but it can be handy depending on your use case.
- Clone or unzip the files to a directory off of your web root. For example,
/combine/
. Change to that directory. composer install
- Rename
.env-sample
to.env
. Set theCOMBINE_BASEDIR
to the directory that will contain your JS/CSS files that you want to allow combining/minification for. - Configure your web server to rewrite URLs, as shown in the examples below. Change the
/combine/
and/minify/
paths as desired.
# Rewrite combine/minify URLs
rewrite ^/combine/(.*)$ /combine/index.php?scripts=$1;
rewrite ^/minify/(.*)$ /combine/index.php?minify=true&scripts=$1;
# Rewrite combine/minify URLs
RewriteRule "^/combine/(.*)$" "/combine/index.php?scripts=$1"
RewriteRule "^/minify/(.*)$" "/combine/index.php?minify=true&scripts=$1"
For example, let's say that you set your COMBINE_BASEDIR
to /var/www/html/scipts/
. Withing this directory, you might have some JS or CSS libraries. We'll combine Font Awesome with the v4 shims as an example, assuming that you have already extracted them to /var/www/html/scipts/dist/css/
.
To combine or minify multiple scripts, separate them with commas:
<!-- Combine example -->
<link rel="stylesheet" href="https://example.com/combine/dist/css/all.min.css,dist/css/v4-shims.min.css" />
<!-- Minify example -->
<link rel="stylesheet" href="https://example.com/minify/dist/css/all.css,dist/css/v4-shims.css" />
Of course, minification is not necessary for scripts that you already have minified versions for. It is merely an option for libraries/scripts that do not contain a minified version. If you have minified versions avaible, it is recommended to simply use the "combine" method as it consumes less system resources.