How to 'minify' Javascript code

Viewed 87789

JQuery has two versions for download, one is Production (19KB, Minified and Gzipped), and the other is Development (120KB, Uncompressed Code).

Now the compact 19kb version, if you download it, you will see is still a javascript executable code. How did they compactify it? And how can I 'minify' my code like that too?

10 Answers

If you are using the VSCode editor, there are lots of plugins/extensions available.

The MinifyAll for instance is a very good one - compatible with many extension.

Install it and reload VSCode. Then click on your file, open command palette (Ctrl+Shift+p), ant type minify this document (Ctrl+alt+m) other available options there also like preserve original document and so on! Easy!

I have written a tiny script which calls a API to get your script minified, check it out:

#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use Fcntl;

my %api = ( css => 'https://cssminifier.com/raw', js => 'https://javascript-minifier.com/raw' );

my $DEBUG = 0;

my @files = @ARGV;

unless ( scalar(@files) ) {
    die("Filename(s) not specified");
}

my $ua = LWP::UserAgent->new;

foreach my $file (@files) {
    unless ( -f $file ) {
        warn "Ooops!! $file not found...skipping";
        next;
    }

    my ($extn) = $file =~ /\.([a-z]+)/;

    unless ( defined($extn) && exists( $api{$extn} ) ) {
        warn "type not supported...$file...skipping...";
        next;
    }

    warn "Extn: $extn, API: " . $api{$extn};

    my $data;

    sysopen( my $fh, $file, O_RDONLY );
    sysread( $fh, $data, -s $file );
    close($fh);

    my $output_filename;

    if ( $file =~ /^([^\/]+)\.([a-z]+)$/ ) {
        $output_filename = "$1.min.$2";
    }

    my $resp = $ua->post( $api{$extn}, { input => $data } );

    if ( $resp->is_success ) {
        my $resp_data = $resp->content;
        print $resp_data if ($DEBUG);
        print "\nOutput: $output_filename";

        sysopen( my $fh, $output_filename, O_CREAT | O_WRONLY | O_TRUNC );
        if ( my $sz_wr = syswrite( $fh, $resp_data ) ) {
            print "\nOuput written $sz_wr bytes\n";
            my $sz_org = -s $file;

            printf( "Size reduction %.02f%%\n\n", ( ( $sz_org - $sz_wr ) / $sz_org ) * 100 );
        }   
        close($fh);
    }
    else {
      warn: "Error: $file : " . $resp->status_line;
    }
}

Usage:

./minifier.pl a.js c.css b.js cc.css t.js j.js [..]

You can use javascript minifier of ubercompute.com to minify your code, It will minify your javascript code upto 75% of their original version.

Try out this JavaScript minifier from fixcode.org. It's a very effective tool to minify JavaScript

  • Import code via URL
  • import from file
  • copy/download output
Related