How to Load external JS files with "load" inside controllers from webjars

Enonic version: XP 6.1.1
OS: Ubuntu

Nashorn supports the “load” function to import external content into the runtime. I can succesfully load scripts from external resources.

Example is use with momentjs.

loadAsset('moment', '');

function loadAsset ( functionIdentifier ,  src ){
    if (typeof functionIdentifier != 'function') {"Load Asset: " + functionIdentifier + " src: " + src );
        load( src );

exports.loadAsset = loadAsset;

And succesfully use in a controller like this:

 var time = new moment(  comment.createdTime ).format("LLL");

I use webjars and I would like to load the resource from the webjars path. Does anyone know what the path looks like is it accessible ?

This is super easy to do with XP.

build.gradle file

dependencies {
    ... other includes and webjars
    webjar "org.webjars:momentjs:2.14.1"

controller file:

var moment =  require('/assets/momentjs/2.14.1/min/moment-with-locales.min.js');

//Then use it as you need.
var myDate = moment(result.createdTime).format('MM:DD:YYYY HH:mm');

You can use moment.js from a webjar on the frontend as well.

All webjars are accessible in the “assets” folder. You won’t see them there in your project files, but they are accessible from a path starting with /assets/<webjar name>. You can see the actual webjar files in your project’s “build” folder at /build/webjars/resources/webjars/momentjs/...


@mla I tried this:

var moment = require('/assets/momentjs/2.14.1/min/moment-with-locales.min.js');

must have made an typo. I’ll try it out.


Works great thanks :slight_smile: