我使用Moment.js同时使用客户端和服务器端来格式化日期。
我想修改Moment.js格式的某些方面,我希望这些修改可以使用单个声明同时应用于服务器端和客户端。
在app.js中,在需要外部.js文件(该文件修改矩对象)之前,我需要时间,但是Node.js一直抱怨在外部.js文件中访问该文件时没有定义该时刻。
我解决这件事的方式就像一个邪恶的黑客:
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, {});发布于 2014-10-04 12:06:55
您可以创建一个返回修改后的moment.js的新模块。您仍然需要在html中包含moment.js,但是不需要在节点中这样做,所以只需在app.js中使用require(__dirname + '/public/modifiedmoment.js')
我稍微修改了这里中的代码,以创建模块。它将用修改后的window.moment代替,并在节点的要求中返回修改后的矩。
(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;
}));https://stackoverflow.com/questions/26192241
复制相似问题