This post requires understanding of how requirejs works and why this could be a challange in XP.
Migrating a Requirejs application from Enonic CMS seemed like a challenge, well first of all because I’m not an expert in Enonic XP and secondly because I read a post of others having issues with this and apparently gave it up.
Actually it was really simple, when you know of the possibillities in XP.
As this was a Enonic CMS application Requirejs requires files from _public. So what I did was to create a _public mapping service in XP (site.xml) - easy:
<mappings>
<mapping controller="/services/_public/_public.js">
<pattern>/_public/.*</pattern>
</mapping>
</mappings>
The service (/services/_public/_public.js) was implemented as follows (ES6 code):
var lib = {
io: require('/lib/xp/io'),
util: require('/lib/enonic/util'),
};
import { toStr } from '/lib/posten/util';
import { respondWithErrorPage } from '/lib/posten/controller';
exports.get = function (req) {
const filename = req.path.replace(/^.*?_public/, '/_public');
const extension = filename.replace(/^.*\./, '.');
const contentType = lib.io.getMimeType(extension);
const file = lib.io.getResource(filename);
log.info(`${filename} (${contentType})`);
const body = file.exists() && lib.io.readText(file.getStream());
if(body === false) {
return respondWithErrorPage(404);
}
return { body, contentType };
};
So XP still delivers, a special thanks to Christian and Bjørnar at Enonic who pointed out the natural solution for this challenge. Oh and you might want to add some nocache headers. The code is ES6 (will not work in ES5) so it is transpiled with babel.
Best regards
Preben, EVRY, working for Konsernportalen Posten Norway.