JavaScript Core Asset Pipeline
This provides the JavaScriptProcessor
base class for building Asset Pipeline processors that run JavaScript with caching, thread safety, and a nice DSL.
Note
|
The JavaScript is currently run using the Rhino engine. Nashorn support might be added at a later date. |
Getting started
dependencies {
compile 'com.craigburke.assets:javascript-core:0.2.4'
}
Example
import com.craigburke.asset.JavaScriptProcessor
import com.craigburke.asset.JavaScriptEngine
import groovy.transform.Synchronized
class ExampleProcessor extends JavaScriptProcessor {
ExampleProcessor(AssetCompiler precompiler) {
super(precompiler)
}
static JavaScriptEngine exampleEngine
@Syncronized
JavaScriptEngine getEngine() { // <1>
exampleEngine = exampleEngine ?: new JavaScriptEngine('transform.js') // <2>
exampleEngine
}
String process(String input, AssetFile file) {
javaScript {
var1 = input // <3>
eval 'transformFunction(var1);' // <4>
}
}
}
-
The getEngine method must be implemented, here we’re just returning a static JavaScriptEngine
-
The JavaScriptEngine constructor can optionally load a file that’s contained on your classpath. Here the file
transform.js
is loaded -
This adds the variable var1 to your JavaScript context with the value of input.
-
The eval method allows you to execute a JavaScript function (or arbitrary JavaScript). The result is returned as a String