I'm using Moment.js both client- and serverside to format dates.
I want to modify certain aspects of Moment.js formatting and I want these modifications to apply both server- and clientside using a single declaration.
In app.js, I require moment before I require my external .js file (which modifies the moment object) but Node.js keeps complaining that moment is not defined when it is accessed in my external .js file.
The way I've solved this feels like an evil hack:
app.js
global.moment = require('moment');
var scripts = require(__dirname + '/public/scripts.js');
index.html
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js">
<script src="/scripts.js">
scripts.js
var moment = (function() {
try {
return global.moment;
} catch(e) {}
try {
return window.moment;
} catch(e) {}
})();
moment.modifySomeProp(prop, {});
You can create a new module that returns a modified moment.js. You still need to include moment.js in your html, but you don't need to do it in node, so you can just use require(__dirname + '/public/modifiedmoment.js') in the app.js
I slightly modified the code from here to create the module. It will replace window.moment with the modified one, and return a modified moment in node's require.
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['moment'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('moment'));
} else {
// Browser globals (root is window)
root.moment = factory(root.moment);
}
}(this, function(moment) {
moment.modifySomeProp(prop, {});
return moment;
}));