minify

So lets make that transpiled file somewhat smaller.

Why would you do that?

Performance: if the file is smalle it will be downloaded faster. The downside is that the file is not readable anymore (and only usefull for production). But when you work with Haxe you really don't care about the transpiled .js file.

How to start

Create a folder named foobar (please use a better name; any name will do) and create folders bin and src. See example below:

+ foobar
    + bin
    + src
        - Main.hx
    - build.hxml

install

Because you will be using NPM by now, I won't explain that. Just install uglify-js and add it to you package.json

npm install uglify-js --save

Because I don't want to have .node_modules folder everywhere if I don't need it, I installed it globally (-g does that)

npm install uglify-js -g

Now install it via Haxelib

haxelib install uglifyjs

and add it to your build file

-lib uglifyjs

that's it!

Every time you will build, you will get an example.min.js as well. You still can use source-map-content as well to map code to the original .hx files.

hello world

Because this is an exercise about minifier, I will use the "hello world" example because its very simple to understand. If you you have any doubt about what to do, read the tutorial again.

So lets create a Main.hx with the following code:

class Main {

    function new() {
        trace("Hello world");
    }

    static public function main() {
        var main = new Main();
    }
}

The Haxe build file, build.hxml

There are a lot of different arguments that you are able to pass to the Haxe compiler. Place these arguments into a text file of one per line with the extension hxml. This file can then passed directly to the Haxe compiler as a build script.

# // build.hxml
# use haxelib
-lib uglifyjs
-cp src
-main Main
-js bin/example.js
-dce full

Build js with Haxe

So as mentioned, you will keep the files you normally generate (in my case example.js and perhaps example.js.map). But extra you get the minified file as well every time you build (example.min.js).

Let's take a short look at the two:

The example.js file

// Generated by Haxe 3.4.5
(function () { "use strict";
var Main = function() {
    console.log("Hello world");
};
Main.main = function() {
    var main = new Main();
};
Main.main();
})();

//# sourceMappingURL=example.js.map

and now the minified/uglyfied example.min.js file

!function(){"use strict";var n=function(){console.log("Hello world")};n.main=function(){new n},n.main()}();

Remember it's meant to look ugly. It's now smaller in bytes.

  • example.js : 219 bytes
  • example.min.js : 107 bytes

And that is just with a small file. You can imagine what it will do with a large application.

results matching ""

    No results matching ""