Preface
Goal: An example of Coffeescript for beginner.
Here, I represent you, a cool template stack: Pug+Stylus+Coffeescript
.
- HTML: Pug
- CSS: Stylus
- Javascript: Coffeescript
Source Examples
You can obtain source examples here:
Let’s get it on.
Start with a little language that,
compile into Javascript called Coffescript
.
Coffescript
Official Documentation
Convert
You can convert your javascript to coffescript using
Install
$ npm i -g coffeescript
Simple Source
Consider this indented coffescript document as below:
document.addEventListener 'DOMContentLoaded', (event) ->
alertButtons = document.getElementsByClassName('dismissable')
i = 0
while i < alertButtons.length
alertButtons[i].onclick = ->
@parentElement.style.display = 'none'
console.log 'Close Button. Element ' + @parentElement.id + ' dismissed'
false
i++
return
It is very similar with Javascript, but without indentation style instead of semicolon.
Command Line
Now you can run this command, to compile the coffeescript into javascript representation:
$ coffee -c --bare js/script.coffee
And the result would be javascript code as below:
// Generated by CoffeeScript 1.12.7
document.addEventListener('DOMContentLoaded', function(event) {
var alertButtons, i;
alertButtons = document.getElementsByClassName('dismissable');
i = 0;
while (i < alertButtons.length) {
alertButtons[i].onclick = function() {
this.parentElement.style.display = 'none';
console.log('Close Button. Element ' + this.parentElement.id + ' dismissed');
return false;
};
i++;
}
});
Without the --bare
options,
your javascript will be in function safety wrapper.
(function() {
...
}).call(this);
Internal Coffescript in Pug
This topic has been discussed in previous article.
What’s Next?
Consider continue reading [ Tools - Task Runner - Grunt ].