【问题标题】:Node.js sharing code between backend and frontendNode.js 在后端和前端之间共享代码
【发布时间】:2021-03-31 17:24:10
【问题描述】:

我想在 node.js 后端和前端之间共享一些代码,例如将某种日期格式(Date 本身不支持)转换为 Date 对象。

首先,如果在后端和前端之间共享代码是一种糟糕的做法,请告诉我。

如果不是:我遇到的问题是对于 node.js,我会使用一个模块,并使用 module.exports 来导出 util 函数。我想避免使用front-end modules 来获得更多浏览器支持。那么如何在后端和前端使用相同的js文件呢?

【问题讨论】:

    标签: javascript node.js node-modules


    【解决方案1】:

    node 和前端使用.js 文件的一种简单方法是在分配给它们之前检查modulemodule.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:// 协议,并简化了在后端或前端运行同样良好的测试代码的编写。

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2016-07-31
      • 1970-01-01
      • 2018-01-15
      • 2021-10-28
      • 2020-03-13
      • 2017-05-08
      • 2021-09-18
      • 2019-07-23
      相关资源
      最近更新 更多