I'm trying to share some simple metadata classes between my nodeJS backend and an Aurelia front end. I can require and use the following from my node (v4.3) process:
"use strict";
class PersonMetadata {
constructor() {
this.relation = ["Spouse/partner", "Child", "Parent", "Other"];
}
}
module.exports.PersonMetadata = PersonMetadata;
but it fails to load in the browser after being processed by the typical Aurelia front end build with:
Error: Cannot read property 'exports' of undefined
How can I structure a module with a class that can be shared between node & Aurelia?
Thought I'd reply with how I got this working. Since my server side node code doesn't currently get processed by gulp I created a shared ES6 class that is directly compatible with node v4.X:
"use strict";
class SharedMetadata {
constructor() {
this.myOptions = ["Democrat", "Republican", "Other"];
}
}
exports.SharedMetadata = SharedMetadata;
This class can be use from node like this:
var SharedMetadata = require('../shared/SharedMetadata').SharedMetadata;
var sharedMetadata = new SharedMetadata();
For the front end this file is processed by the normal Aurelia build\transpile step, but the file will have an error with the exports statement.
So I added another gulp build step that runs only on the "shared" files after the transpile step that fixes up the errors and does a "proper" export:
gulp.task('transform-shared', function() {
return gulp.src(paths.outputShared + '**/*.js')
.pipe(replace(/exports\.(.*) = (.*);/g, "_export('$1', $2);"))
.pipe(gulp.dest(paths.outputShared));
});
This replaces the exports statement with:
_export('SharedMetadata ', SharedMetadata );
Then the class can be used like any "normal" Aurelia front end class.