Skip to content

Examples

Shane Brinkman-Davis Delamore edited this page Apr 10, 2017 · 7 revisions

Try CaffeineMC Out

In node:

require('caffeine-mc/register')
require('caffeine-mc/examples/javascript')
require('caffeine-mc/examples/coffeescript')
require('caffeine-mc/examples/custom')

output:

> require('caffeine-mc/register')
Neptune.CaffeineMc
> require('caffeine-mc/examples/javascript')
Hello from JavaScript!
{}
> require('caffeine-mc/examples/coffeescript')
Hello from CoffeeScript!
{}
> require('caffeine-mc/examples/custom')
[ 'This',
  'Converts',
  'MultiWordWords',
  'NoMatterWhatTheyLookLike',
  'To',
  'UpperCamelCase' ]

BabelJs

CaffeineMC doesn't automatically install BabelJs, so before you try this example, install:

npm install babel-core
npm install babel-preset-es2015

In node:

require('caffeine-mc/register')
require('caffeine-mc/examples/babel')

output:

> require('caffeine-mc/register')
Neptune.CaffeineMc
> require('caffeine-mc/examples/babel')
'Hello from ES6 => ES5 curtesy of Babel.'

Source

javascript.caf

|JavaScript

// this is JavaScript
(function(){console.log("Hello from JavaScript!")})()

coffeescript.caf

|CoffeeScript
# "|CoffeeScript" tells CaffeineMC the rest of the file will be compiled in CoffeeScript.

# this is CoffeeScript
do -> console.log "Hello from CoffeeScript!"

custom.caf

|CoffeeScript
  ###
  - Because of '|CoffeeScript' above, this whole block and the rest of the file
    is interpreted as CoffeeScript.
  - Everything to the end of this indented block runs at compile-time!
  - this/@ is set to the current CaffeineMc instance.
  - A new CaffeineMc instance is created for every .caf/.caffeine file compiled.
  ###

  # Require whatever you want!
  {upperCamelCase, w, log} = require 'art-standard-lib'

  ###
  Set @compile to an object with a compile function
  to define your own custom complier.
  ###
  @compiler = compile: (source) ->
    strings = for word in w source
      "'#{upperCamelCase word}'"

    "module.exports = [\n  #{strings.join ",\n  "}\n];"

This converts multi-word-words, no_matter_what_they_look_like to upperCamelCase

babel.caf

|
  var
    Babel   = require('babel-core'),
    es2015  = require('babel-preset-es2015');

  this.compiler = class BabelWrapper {
    static compile(source) {
      return Babel.transform(source, {
        presets: [es2015]
      });
    }
  };

module.exports = class Foo {
  static bar() {return "Hello from ES6 => ES5 curtesy of Babel."}
}.bar();