jsRealB use cases : Examples and Patterns

This page illustrates ways of embedding jsRealB in web pages or in JavaScript application, Node.js in particular. Of course, there are many other possibilities, but these examples can serve as starting points.

This application realizes the following three sentences: one in English, one in French and a bilingual one.

These examples use the examples-functions.js script with four functions that take for granted that the jsRealB functions are available in their environment:

This JavaScript file can be used as a module by adding an export statement to the previous script such as the following:

export {addExp, en, fr, enfr}

This script examples-functions-module.js can also be used directly as a node script as will be shown below.

The appropriate environment for using these function can be provided in different ways.

• Web page loading jsRealB with a script tag [Look at the source of this page]

The simplest use case is when the realization is done on the web page that loads jsRealB with this script tag.

        <script src="/path/to/jsRealB.js"></script>    

This creates the jsRealB object, to use the functions without prefix, they can be added to the global environment with


before calling any other jsRealB function.

Node.js module [Look at this script]

The same module script can be used either imported or used alone, this is useful for unit testing. But in this case, it is sometimes useful to have a slightly different behavior depending on the context. To check if a script is called from a Node.js or not, the following JavaScript snippet can be used:

typeof process !== "undefined" && process?.versions?.node
which returns true when executed in a Node.js environment. jsRealB provides the variable isRunningUnderNode (see function addExp() ) but of course, it must have been loaded to be used, which is unfortunately not always the case, as often this test is used to check we should load jsRealB!. It would also be possible to check typeof jsRealB == "undefined". This module can also be imported by another Node.js script.

• Web page without a script tag [Look at the source of this page.]

jsRealB can also be loaded as a JavaScript module as follows:

        <script type="module">
            import "../dist/jsRealB.js"; 
            import {addExp,en,fr,enfr} from "./examples-functions-module.js";

Useful pattern

The following code organisation has proven itself useful for many JavaScript files in a web environment that are used either as node module or as from a web page for which jsRealB has been loaded with the script.

        if (typeof process !== "undefined" && process?.versions?.node){ // cannot use isRunningUnderNode yet!!!
            let {default:jsRealB} = await import("../../dist/jsRealB.js");
            // .... start of the application     
        } else {
            $(document).ready(function() { // for jQuery
                // .... start of the application