RequireJS: how to load JavaScript code in Niagara 4

When using BajaScript version 1 in Niagara AX, the following script tag was required for BajaScript to work:

<script type="text/javascript" src="module://bajaScript/com/tridium/bajascript/bs.min.js"></script>

The more complex the web application, the more script tags are needed. This can have some negative effects on your web application:

As more developers transition their UI from Java to HTML5, we need a modular way to manage JavaScript. To solve this problem, we use RequireJS from https://requirejs.org. RequireJS uses the Asynchronous Module Definition (AMD) method of loading JavaScript code.

RequireJS has a wide variety of configuration options, but in most cases, Niagara will completely handle the configuration of it for you. The most important thing to learn about using RequireJS in Niagara is the AMD syntax itself.

// to define an AMD module:
// myModule-ux/src/rc/MyWidget.js
define([
  'baja!',
  'bajaux/Widget' ], function (
  baja,
  Widget) {
  
  return class MyWidget extends Widget {
  };
});

// to consume an AMD module:
define([
  'nmodule/myModule/rc/MyWidget' ], function (
  MyWidget) {
  // write code that uses MyWidget here
});

What resources can I access via RequireJS?

How do I build my web module using RequireJS?

In addition to loading code in the browser at runtime, RequireJS allows multiple JS modules to be bundled up into single files. This improves caching and load times, and reduces pressure on a station’s web server.

Please see the section on Building JavaScript Applications for details.

How do I include RequireJS itself in my web application?

Depending on how you are developing a web application, your use of RequireJS will vary slightly.