如何使用单个声明修改服务器端和客户端都使用的库

How can I modify a library that is used both server- and clientside using a single declaration?

本文关键字:客户端 单个 何使用 声明 修改 服务器端      更新时间:2023-09-26

我在客户端和服务器端都使用Moment.js来格式化日期。

我想修改Moment.js格式的某些方面,我希望这些修改使用一个声明同时应用于服务器端和客户端。

在app.js中,我在需要外部.js文件(它修改了moment对象)之前需要moment,但Node.js一直抱怨在我的外部.js中访问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,但您不需要在节点中包含,所以您可以在app.js 中使用require(__dirname + '/public/modifiedmoment.js')

我从这里稍微修改了代码以创建模块。它会将window.moment替换为修改后的,并在节点的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;
}));