我在客户端和服务器端都使用 Moment.js 来格式化日期。
我想修改 Moment.js 格式的某些方面,并且希望使用单个声明将这些修改应用到服务器端和客户端。
在 app.js 中,我在需要外部 .js 文件(修改 moment 对象)之前需要 moment,但 Node.js 一直提示在我的外部 .js 文件中访问 moment 时未定义 moment。
我解决这个问题的方式感觉像是一个邪恶的黑客:
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, {});
最佳答案
您可以创建一个返回修改后的 moment.js 的新模块。您仍然需要在 html 中包含 moment.js,但您不需要在 Node 中执行此操作,因此您只需使用 require(__dirname + '/public/modifiedmoment.js')
在 app.js
我稍微修改了 here 中的代码创建模块。它将用修改后的值替换window.moment,并在 Node 的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;
}));
关于javascript - 如何使用单个声明修改同时在服务器端和客户端使用的库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192241/