Basic Concepts

The code snippets in the introduction shouldn't look too strange if you're familiar with HTML and JSTL. You saw tags that looked just like HTML tags, and dynamic content in {} curly braces much like ${} in JSTL expression language. This HTML-like syntax is called JSX.

It was developed by Facebook for use with their React.js JavaScript framework. Roughly speaking, JSX is like an extension of XML. That is to say, pretty much anything you can write in HTML or JSTL will be valid JSX, with a couple exceptions. If you took a JSX parser and gave it any random chunk of code from a JSP file, chances are it would accept it with no problem.

Since we are using JSX to generate HTML and JSTL, it makes sense that it should look similar. But what makes it useful is that, under the hood, it is very different.

JSX is actually JavaScript

Before actually generating HTML/JSTL, that build task transforms JSX into JavaScript. A piece of JSX like this...

<div id="greeting">Hello, World!</div>

...will end up transformed into this:

jsxQuery.createElement("div", { id: "greeting" }, "Hello, World!");

Each JSX element is actually a call to that createElement method in disguise. The tag name is the first argument, the attributes become the second argument, and the element's children come last. The build task then uses all those arguments to produce the final markup.

It may seem strange to transform what looks like HTML into JavaScript, especially when it's going to end up as HTML anyway. But this is what will make it possible to plug in test data later. You can't do that with plain HTML. For that, you need the versatility of a full programming language like JavaScript. By using JSX, we get both the power of JavaScript and the familiarity of HTML.

jsxQuery uses Node

To be clear, we are still just generating JSP files. We are using JavaScript to do this, but this JavaScript code we are writing is not going run in the browser. Our build task runs in Node.js. You'll have to install it on your machine in order to use jsxQuery.

If you've only ever run JavaScript in the browser before, there's just one big difference you need to know for now. When you're running JavaScript code in Node, you can reference code from other files using its module system.

Node modules in a nutshell

So if you had a file greeting.js like this:

var greeting = 'Hello';
module.exports = greeting;

That string greeting would be available even outside greeting.js because you exported it. Say you also had a file hello-world.js in the same folder, with contents like this:

var helloWorld = require('./greeting') + 'world!'
console.log(helloWorld);

You could run $ node hello-world.js and you would see Hello world! printed in the terminal. You import values from other JavaScript files using that require function.

Once you have Node installed and you understand the concept of modules, you're ready to start using jsxQuery.

results matching ""

    No results matching ""