WebDev.sh

Online Web Development tools. All free, all provide an API. Simple Quick and Fast!

JavaScript Minifier can now process ES6+ code

JavaScript Minifier now has greater powers. It is no longer ES5 only and can now minify ES2015 (ES6) and above code! This has been a long time coming but it has been worth the wait.

So, let me give you an example. In the past if you tried to minifiy the following code, you'd receive back only an error on the first line at the 2nd set of brackets:

setTimeout(() => {
  console.log('Ping')
}, 1 * 1000)

But now we get the expected minified output of:

setTimeout(()=>{console.log("Ping")},1e3);

(And as a bonus, I love how the 1 * 1000 is pre-calculated and is output as 1e3.)

Terser

We switched out uglify-js which is both deprecated, unmaintained, and doesn't support ES6+, for a fork of it called Terser. It is a wonderful package written/maintained by Fábio Santos (@fabiosantosart) and was a joy to add as a drop in replacement for uglify-js. Let's take a look at the commit diff so you can see how easy it was to use.

commit 1a466a3620e13affcfd997178e13720b5bbfa736
Author: Andrew Chilton <andychilton@gmail.com>
Date:   Fri Mar 1 10:08:14 2019 +1300

    Switch to Terser

diff --git a/lib/minify.js b/lib/minify.js
index 66cfcdc..1d8e8a8 100644
--- a/lib/minify.js
+++ b/lib/minify.js
@@ -6,18 +6,16 @@ const path = require('path')

 // npm
-const uglify = require('uglify-js')
+const terser = require('terser')
 const redis = require('redis')

@@ -58,7 +56,7 @@ function doit(rid, js, callback) {
   // Here, there are three things to do:
   // 1. Write the file to the filesystem
   // 2. Check the md5 and see if we have a cached file. If so, send it.
-  // 3. Call UglifyJS to minify the input to the output
+  // 3. Call Terser to minify the input to the output
   // 4. Send the result back.

   // write this input to a file
@@ -116,9 +114,9 @@ function doit(rid, js, callback) {
           var minified = ''

           // perform the minification, and check for any error
-          const result = uglify.minify(js)
+          const result = terser.minify(js)
           if ( result.error ) {
             minified = [
               '// Error : ' + result.error.message,
diff --git a/package.json b/package.json
index 276ebf3..cf3edfd 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
     "redis": "^2.8.0",
     "rustle": "^0.3.1",
     "serve-favicon": "^2.4.5",
-    "uglify-js": "^3.3.7",
+    "terser": "^3.16.1",
     "yid": "^1.0.0"
   },
   "author": {

Pretty simple aye! :) I highly recommend you all switch from uglify-js or uglify-es to terser. Simple, drop in replacement, with the ability to minify modern JavaScript.

Have fun!

Tags: es2015 es2016 es2017 es2018

Posted: 3 months ago