亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Node.js和瀏覽器之間共享代碼?

如何在Node.js和瀏覽器之間共享代碼?

搖曳的薔薇 2019-10-05 11:19:57
我正在使用JavaScript客戶端(在瀏覽器中運行)和Node.js服務器創建一個小型應用程序,并使用WebSocket進行通信。我想在客戶端和服務器之間共享代碼。至少可以說,我才剛剛開始使用Node.js,而我對現代JavaScript的了解還有些生疏。因此,我仍然對CommonJS require()函數有所了解。如果我使用“導出”對象創建程序包,那么我將看不到如何在瀏覽器中使用相同的JavaScript文件。我想創建一套在兩端使用的方法和類,以方便編碼和解碼消息以及其他鏡像任務。但是,Node.js / CommonJS打包系統似乎使我無法創建可在兩側使用的JavaScript文件。我也嘗試使用JS.Class來獲得更嚴格的OO模型,但是我放棄了,因為我無法弄清楚如何使提供的JavaScript文件與require()一起使用。我在這里想念什么嗎?
查看完整描述

3 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

如果您想編寫一個既可以在客戶端又可以在服務器端使用的模塊,那么我有一篇簡短的博客文章,介紹了一種快速簡便的方法:為Node.js和瀏覽器編寫,實質上是以下內容(this與相同window) :


(function(exports){


    // Your code goes here


   exports.test = function(){

        return 'hello world'

    };


})(typeof exports === 'undefined'? this['mymodule']={}: exports);

另外,也有一些旨在在客戶端實現Node.js API的項目,例如Marak的gemini。


您可能還對DNode感興趣,它使您可以公開一個JavaScript函數,以便可以使用基于JSON的簡單網絡協議從另一臺計算機上調用它。


查看完整回答
反對 回復 2019-10-05
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

檢出使它能夠在Node.js模塊模式,AMD模塊模式以及瀏覽器中的全局模式下工作的jQuery源代碼:


(function(window){

    var jQuery = 'blah';


    if (typeof module === "object" && module && typeof module.exports === "object") {


        // Expose jQuery as module.exports in loaders that implement the Node

        // module pattern (including browserify). Do not create the global, since

        // the user will be storing it themselves locally, and globals are frowned

        // upon in the Node module world.

        module.exports = jQuery;

    }

    else {

        // Otherwise expose jQuery to the global object as usual

        window.jQuery = window.$ = jQuery;


        // Register as a named AMD module, since jQuery can be concatenated with other

        // files that may use define, but not via a proper concatenation script that

        // understands anonymous AMD modules. A named AMD is safest and most robust

        // way to register. Lowercase jquery is used because AMD module names are

        // derived from file names, and jQuery is normally delivered in a lowercase

        // file name. Do this after creating the global so that if an AMD module wants

        // to call noConflict to hide this version of jQuery, it will work.

        if (typeof define === "function" && define.amd) {

            define("jquery", [], function () { return jQuery; });

        }

    }

})(this)


查看完整回答
反對 回復 2019-10-05
  • 3 回答
  • 0 關注
  • 763 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號