Is it possible to make JavaScript module compatibl

2019-04-20 16:17发布

问题:

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