It’s just data

DSL for JavaScript

W

Jeremy Ashkenas: “work towards building a language that is to ES6 as CoffeeScript is to ES5”… close, but—do it for [ES6+HTML+CSS], and you’ll win ;)

It occurs to me that there is a shortcut available.  Let a library like React replace [ES6+HTML+CSS].  Then build a DSL for that library.

JavaScript isn’t exactly known for its ability to build DSLs.  Ruby, however, is.  And has an excellent parser library.  By transforming the AST, I can convert calendar.js.rb into calendar.js.

In the process, I start by replacing JSX with a library which was inspired by Builder, Markaby, and Tagz.  These libraries, in turn were presumably inspired by earlier works like Perl’s CGI.

But there is more.  JSX can’t directly express iteration.  Look at CommentList from the React tutorial.  Instead you build up a list, and then subsequently wrap that list.  For nested lists, it appears worthwhile to split out separate components.  There is nothing wrong with doing that, but I will suggest that the primary reason to split out a component shouldn’t be to pander to the limitations of the programming language syntax.

In Ruby you can directly express iteration.  So where a comment box in the tutorial takes four classes, an entire calendar month can be expressed in one.

And there is even more.  Functions in JavaScript are the swiss army knives of programming language features.  The can be used to express classes, blocks, lambdas, procs.  But this flexiblity comes at a price.  Ruby2JS can detect when idioms like var self=this are needed and automatically apply them.

The net is that I can write smaller, more understandable code.  And in the process focus more on the problem I’m trying to solve.

Like with CoffeeScript, "It’s just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.  You can use any existing JavaScript library seamlessly from Ruby2JS (and vice-versa). The compiled output is readable and pretty-printed, will work in every JavaScript runtime, and tends to run as fast or faster than the equivalent handwritten JavaScript.

Now I don’t expect to have the success or impact that CoffeeScript has had.  But I can say that I’m having fun.  And in the process, I’m seeing the benefits with applications I write.


Add your comment