With grooscript, you can convert your groovy code to javascript. We will use gradle to create a static web project, with html file and some .js files. Application logic done in groovy, and run in the browser because groovy code is converted to javascript.

Let’s use grooscript gradle plugin to play with grooscript. Install gradle if you don’t have it installed in your machine. You can use Gvm to install gradle 2.1+. Is important you use at least gradle 2.1, because grooscript works with groovy 2.0+ and we will use new plugin system in this demo. After install gradle, just create a new folder and move to it.

Creating project

Create a build.gradle file with the grooscript plugin data and gradle wrapper.

plugins {
  id "org.grooscript.conversion" version "1.2.3"
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.11'
}

Run > gradle wrapper to create gradlew executable. Run > ./gradlew task to see grooscript tasks.

Let’s start with initStaticWeb task to create a html static project. Run > ./gradlew initStaticWeb and the plugin will create the following files.

├── build.gradle
└── src
    └── main
        ├── groovy
        │   └── Presenter.groovy
        └── webapp
            ├── index.html
            └── js
                ├── app
                └── lib
                    ├── grooscript-tools.js
                    ├── grooscript.min.js
                    └── jquery.min.js

Now, let’s open index.html in your browser, for example running > open src/main/webapp/index.html open my Google Chrome. You must see an input text with label Name: and a button Say hello!. If you put your name and press button nothing happens. In javascript console you can see the error, a file called Presenter.js not found in src/main/webapp/js/app.

I introduced this error to show you that you have to convert your groovy code to javascript each time you change your groovy files. We will see later that you can run a daemon to automatically convert your code when a file change is detected. But for now, it’s important that you understand that your groovy code isn’t running in your browser, the javascript converted code is. To convert your groovy code to javascript, run > ./gradlew convert and a new javascript file is generated, the missing file in the browser error.

└── src
    └── main
        └── webapp
            └── js
                └── app
                    └── Presenter.js

Now, go the browser, reload the page, put your name and press Say hello!. The text Hello your_name! will be append to the page. So, nice, all is working, and the code that is running in your browser, is Groovy code. The file Presenter.groovy is a groovy file, that has been converted to javascript Presenter.js with grooscript. You can test the groovy class with a spock and use your favorite groovy IDE. This is one of the reasons to use grooscript, you use the tools you know to create groovy code that runs in your browser.

Playing

Now, let’s take a look to index.html code.

<html>
<head>
    <title>Initial static web page</title>
    <script type="text/javascript" src="js/lib/jquery.min.js"></script> (1)
    <script type="text/javascript" src="js/lib/grooscript.min.js"></script> (2)
    <script type="text/javascript" src="js/lib/grooscript-tools.js"></script>
    <script type="text/javascript" src="js/app/Presenter.js"></script> (3)
</head>
<body>
    <p>Name:<input type="text" id="name"/></p> (4)
    <input type="button" id="button" value="Say hello!"/> (5)
    <div id="salutes"/> (6)
    <script type="text/javascript">
        presenter = Presenter(); (7)
        $(document).ready(function() {
            var gQuery = GQueryImpl(); (8)
            gQuery.bindAll(presenter); (9)
            console.log('All binds done.');
        });
    </script>
</body>
1 Grooscript itself doesn’t requires jquery, but some of the tools in grooscript-tools.js does.
2 This js contains grooscript core. Is needed to run any code converted with grooscript.
3 This is the converted javascript code generated from Presenter.groovy.
4 The input text with id name.
5 The button with id button.
6 The div where all salutes are added.
7 Creation of the class, to create a class generated with grooscript, don’t use new.
8 Use jQuery implementation, that comes in grooscript-tools.
9 Bind methods and properties to dom objects. Now name input is binded to presenter.name property. And when you press the button, method presenter.buttonClick() is executed.

Is very important, all code that you convert to javascript, using grooscript, it needs grooscript.js or minified grooscript.min.js. If you take a look at Presenter.js you will see some functions that starts with gs.xx. For example if you call a method, maybe the method doesn’t exist, groovy is a dynamic language, and maybe at runtime that method exists or not, or maybe there is a methodMissing call. grooscript.js resolves method calls, access to properties, java / groovy types,…​ If you use grooscript generated code in other pages or environments, remember include any of this libraries.

Now, you can start to modify Presenter.groovy, much better if you create a Spock test for it. When you make a change, remember that you have to generate the javascript code with > ./gradlew convert. So in a typical grooscript workflow, you are working with your groovy code, and see the results in your browser, no class loading issues, just reload the page with the changes in your javascript generated files. But is boring run convert all the time, much better if you run > ./gradlew daemon. This daemon blocks execution of gradle, and will listen changes in your groovy files. Each time a groovy file changes, groovy code will be converted to javascript. Until you break gradle with ^C.

Conversion options

Is very important understand grooscript conversion options. In this example some options are used, the gradle plugin has some default conversion options. What files have to be converted? Where .js files are saved?…​

source

Files or folders with files to be converted. If you put a folder, all groovy files inside will be converted. For example: ['src/grooscript', 'MyGroovyFile.groovy']

destination

The folder or .js file where javascript files are generated, and no folders inside will be created. For example: 'web-app/js'

classpath

List of folders or jar’s to find dependencies. Before groovy code is converted to javascript, that code have to be successfully compiled. For example: [''src/groovy'']

customization

to each file to be converted, will be applied a groovy customization. For example you can for example type check all the groovy classes to be converted with { -> ast(TypeChecked)}

initialText

you can add test at the beginning of your converted javascript file. You can add comments or javascript code. For example: ''//This code has been generated with grooscript''

finalText

like initialText, but at the end of the converted file. For example: ''MyClass().init();''

recursive

if you specify a folder with the source conversion option, by default will not convert files inside folders. To convert recursive, just set to true

mainContextScope

you can help the converted, specifying functions and variables that will be availables in the main context of the javascript environment. For example: [''$'', ''window'',''myFunction'']

addGsLib

you can add a grooscript js lib at the beginning of the converted file. For example you can add grooscript.js to the result, and then you don’t have to worry about include that dependency in javascript ''grooscript''

requireJsModule

the result javascript code will be as a require.js module.

consoleInfo

you get info in console about conversion process setting to true. Is mainly a debug option.

includeDependencies

in the result javascript file, will be added conversion of dependencies. You can’t set both includeDependencies and requireJsModule to true.

nashornConsole

when you set to true, then in javascript will be used 'print' function to write in console. 'console.log()' in sot supported by Nashorn.

The default conversion options of the grooscript gradle plugin are:

source = ['src/main/groovy']
destination = 'src/main/webapp/js/app'
classpath = ['src/main/groovy']
convertDependencies = false

You can change, or set new options in your build.gradle, for example with this new options:

grooscript {
    source = ['src/main/groovy/presenters']
    destination = 'js'
    classpath = ['src/groovy']
    convertDependencies = true
    mainContextScope = ['$', 'window', 'Handlebars']
    initialText = '//Grooscript converted file'
}

Javascript code in your groovy code

If you are reading this, and you have started to play with grooscript, maybe you have thought about put javascript code in your groovy code. Imagine you want to use a javascript library, and you want to init it, but in the init method of your groovy class that will be converted to javascript. For example, in this class, initDrawScene is a javascript function to initialize a canvas scene with a draw method:

class Draw {
    def points
    def scene
    def init() {
        points = [3, 4, 45, 65]
        initDrawScene()
        drawPoints()
    }
    def drawPoints() {
        points.each {
            scene.draw it
        }
    }
}

With grooscript you can put javascript code in a groovy method using @GsNative annotation.

import org.grooscript.asts.GsNative

class Draw {
    ...
    @GsNative
    def initDrawScene() {/*
        //This is just javascript code that will be used in your javascript converted method
        this.scene = canvas.init({x: 400, y: 200});
    */}
    ...
}

You have to add grooscript dependency to your project in your build.gradle:

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.grooscript:grooscript:1.2.3'
}

Conclusion

I have shown a good way to play with grooscript. It’s time you start to play with it. Just code in groovy and see the results in your browser. You know conversion options and some grooscript tips. There are more tips, more helper classes in grooscript-all.js as the html builder or the jquery bean.

This is just a introduction to grooscript, more things to discover as the grails plugin or the Node.js support. Grooscript is just a tool that allow you create javascript code from your groovy code. You don’t have to repeat code in your server side and client side, you can just convert it, for example for your validations or your pogo''s.

You can see an example of a spring boot application using grooscript deployed in the cloud, the source code is in github.

Please, if you have comments, suggestions, problems,…​ don’t hesitate to contact me at grooscript@gmail.com, or open an issue or feature in Github. This is an open source project and your feedback is more than welcome to improve it. More guides come in the future, also can find more documentation in grooscript site.