Is it possible to make JavaScript module compatible with both NodeJS and RequireJS?

╄→гoц情女王★ 提交于 2019-12-06 20:52:16

问题


I have been investigating how various module concepts can be applied within NodeJS and browser applications using the the NodeJS require (obviously in NodeJS apps) and RequireJS for the web browser environment.

It then dawned on me that some modules may be useful for use by both the client and server applications and thus could be reused.

How can modules be developed so that they are compatible with both of these environments?

One is synchronous and one asynchronous. My first thought was to utilise the asynchronous syntax and then to define a custom module for NodeJS which simply invokes the asynchronous callback, synchronously. But how would the RequireJS-emulator be included into the cross-environment module without first using the NodeJS synchronous callback?


回答1:


See this post : Bridging the module gap between Node.js and browsers




回答2:


See also the set of boilerplates at https://github.com/umdjs/umd

About async vs. sync -- for define() in Node, it is common to just use synchronous execution of the factory function passed to define. That is how requirejs works when running in Node.




回答3:


The http://uRequire.org project bridges the gaps of the AMD & nodejs / commonJs formats. U can write in either (or both), and execute / deploy to any of the two or a standalone.js.




回答4:


check this resource here: it's Not Hard: Making Your Library Support AMD and CommonJS it explains everything very well I will post the take-away code you need, but to understand everything you should read that article

by this code, you added AMD(requireJs) and Node support for your js library

(function (global, factory) {
    if (typeof define === 'function' && define.amd)
        define(['jQuery'], function ($) {
            return (global['toaster'] = factory($))
        });
    else if (typeof module === "object" && module && typeof module.exports === "object")
        module.exports = (global['toaster'] = factory(require('jquery')));
    else global['toaster'] = factory(global['jQuery']);
})(this, function ($) {
    // implementation goes here
    var myModule = {};
    return myModule;
    function helper() {
    }
})

one more thing, I found out this Universal Module Definition GitHub project for all variant implementations you can check them all



来源:https://stackoverflow.com/questions/8263944/is-it-possible-to-make-javascript-module-compatible-with-both-nodejs-and-require

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!