在node 和前端使用.js 文件的一种简单方法是在分配给它们之前检查module 和module.export 对象。
convert-date.js 文件示例:
function convertDate(date) {
// blah blah
}
if(this && typeof module == "object" && module.exports && this === module.exports) {
module.exports = convertDate; // for example
}
这导致在前端将convertDate 声明为全局函数名,同时允许在节点中使用它
const convertDate = require(pathOfConvertDate.js);
为了限制创建的全局变量的数量,将更复杂的代码放在返回要导出的值的 IIFE 中:
const convertDate = (()=>{..... return convertDate;})();
if( this etc...) module.exports = convertDate;
上面的一个变体是要求前端必须存在一个公共实用程序对象,该对象必须在文件包含之前声明。使用Util作为示例名称,导出代码变得更像
if(this && typeof module == "object" && module.exports && this === module.exports) {
module.exports = convertDate; // for example
}
else if(typeof Util == "object" && Util) {
Util.convertDate = convertDate;
}
else {
throw( Error("Front-end 'Util' export object not found'));
}
FWIW 我不知道这种用法有多普遍。我确实知道它适用于file:// 协议,并简化了在后端或前端运行同样良好的测试代码的编写。