All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sweetjs-0.2.5.node_modules.sweet.js.index.md Maven / Gradle / Ivy

---
layout: default
---

# Sweeten Your JavaScript

Sweet.js brings the hygienic macros of languages like Scheme and Rust to
JavaScript. Macros allow you to sweeten the syntax of JavaScript and
craft the language you've always wanted.

Do you want to use class syntax but don't want to wait for ES6? Add
them yourself with just a couple lines of code!

    // Define the class macro here...
    macro class {

      rule {

        $className {
            constructor $cparams $cbody
            $($mname $mparams $mbody) ...
        }

      } => {

        function $className $cparams $cbody

        $($className.prototype.$mname
          = function $mname $mparams $mbody; ) ...

      }

    }

    // An now classes are in JavaScript!
    class Person {
      constructor(name) {
        this.name = name;
      }

      say(msg) {
        console.log(this.name + " says: " + msg);
      }
    }
    var bob = new Person("Bob");
    bob.say("Macros are sweet!");

To get a better sense of what macros can do, check out some
[example macros](https://github.com/mozilla/sweet.js/wiki/Example-macros)
or play around with macros in the online [editor](browser/editor.html).

# Getting sweet.js

Install the sweet.js compiler via npm:

    $ npm install -g sweet.js

Use the `sjs` binary to compile your sweet.js code:


    $ sjs -o output.js my_sweet_code.js

* Write macros in the online [editor](browser/editor.html)
* Report issues on
  [github](https://github.com/mozilla/sweet.js/issues).
* As for help at #sweet.js on irc.mozilla.org.
* Join the [mailing list](https://groups.google.com/forum/#!forum/sweetjs).
* Ping [@disnet](https://twitter.com/disnet) on Twitter.

# Getting Started 

You can think of macros as functions that work on syntax. Much like
a normal function you write a macro *definition* and then later
*invoke* the macro with a syntax argument to produce new syntax.
Running sweet.js code through the compiler will *expand* all macros
and produce pure JavaScript that can be run in any JS environment.

Sweet.js provides two ways to define a macro: the simpler
pattern-based *rule* macros and the more powerful procedural *case*
macros (if you are familiar with Scheme or Racket these correspond to
`syntax-rules` and `syntax-case`). 

## Pattern-Based Macros -- Macros Rule!

Rule macros work by matching a syntax *pattern* and generating new
syntax based on a *template*.

To define a macro sweet.js provides a new `macro` keyword that looks
something like this:

    macro  {
      rule {  } => {