Skip to content

Synchronous Require

anodynos edited this page Jun 27, 2013 · 1 revision

You can use the simple require('depdir/dep') anywhere you like (nodejs or AMD), without any worries: there is automation.

No more 'require', 'module', 'exports' declarations

When authoring in AMD, you dont need to define 'require' as an AMD dependency, or use a param 'module', 'exports' when you use the nodejs require('') notation. Its done for you:

  • Just write your module using AMD structure define(['dep1'],fn(dep1){}) declaring only your real dependencies. Then in your module code you can use require('dep2') as you would normally do on nodejs - no need to add 'require' as the first dependency on [].

  • or use the plain nodejs/commonjs notation with var m = require('m'), having a module.exports = myModule; somewhere.

Your module is ready to be trasnlated to AMD, UMD, nodejs and plain <script/>.

Never miss a dependency

In RequireJS/AMD runtime, if you have a require('myDep') in your main module (factory) code, there are two cases:

  • You are using the simplified define wrapper, i.e you have NO dependencies array and have passed require (& perhaps module', exports) as the only parameter(s). RequireJS actually 'scans' your module code at runtime, prefetching all deps in require('dep') calls, before executing your module code. This works fine, if you stick to it (although it might cost on runtime speed).

  • You do have some array dependencies of your own, and these are preloaded before executing your module. But if you have even one array dep (even 'require'), requireJS doesn't scan for require calls to preload at runtime. So, in a require('myDep') call if you forgot to declare 'myDep' in the array dependencies [], your module/app will appear as halted.

uRequire automatically fills missing require('') dependencies from [] declarations, naturally after having resolved their paths. Hence, when authoring in AMD in uRequire, you only need to declare deps only once & when you need them, just like in require('myDep') nodejs format.