Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 827
Lea Hayes Avatar asked Nov 25 '11 01:11

Lea Hayes


People also ask

Is RequireJS outdated?

RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.

Which type of modular come along with NodeJS installation?

Node. js comes with the npm package manager. Using it, you can install, uninstall and search for Node. js modules.

Should I use ES6 modules or CommonJS?

Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file. Below is common usage of those.

Does Node use RequireJS?

Yes! The Node adapter for RequireJS, called r. js, will use Node's implementation of require and Node's search paths if the module is not found with the configuration used by RequireJS, so you can continue to use your existing Node-based modules without having to do changes to them.


2 Answers

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

like image 175
pradeek Avatar answered Sep 20 '22 00:09

pradeek


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.

like image 45
jrburke Avatar answered Sep 22 '22 00:09

jrburke