fredag 4 april 2014

What's the deal with sweet.js?

I had heard people giving praise for sweet.js, but couldn't figure out what all the buzz was about. But I decided to give it a go, and found it really good. I'm going to try to explain why I like it.

Sweet.js is quite different from Coffeescript, Typescript or Dart. These are languages that can be compiled to Javascript.

Now, Sweet.js on the other hand is not another language. In fact, after you've set up your environment to build your  Sweet.js files, you get no benefits. You still write the exact same Javascript as before. But what you get is the possibility to enhance the language.

Lets say you find yourself writing this repeatedly:

JSON.stringify(obj)

You could install a macro from npm:

npm install git+https://github.com/me97esn/conosle-macros.git --save-dev

that lets you write the following code instead:

obj as string

When sweet.js finds the above 'as string' it replaces it with JSON.stringify(obj).
But everything else is just plain Javacript.

Or let's say you would like to use the following syntax to create a range:

0 ... 10

That's totally possible. Sweet.js will replace it with
[
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
];

See example here.

That macro is included in the above installed npm package. Just tell the sweet.js grunt task to use conosle-macros/range.sjs (or conosle-macros/macros.sjs to get all of them) and that's possible.

Just as ES6 fat arrows which allows you to write

()=>;

Instead of

function(){}

So, by installing the above macros
I can now write:
(0 ... 10).map((x)=>x *x)

Instead of writing

[
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
].map(function (x) {
    return x * x;
}.bind(this));

Pretty neat, isn't it?

And what if you have different needs than me? Well, writing macros yourself is pretty straightforward. Just go ahead. Create some macros, publish them in npm and make the Javascript world a better place!

Inga kommentarer:

Skicka en kommentar