Andy
Andy

Reputation: 751

require.js require inside a require

Why do we want to have another require structure inside a require structure?

like

require([mod1,mod2], function(m1, m2){

  require([mod3], function(m3){
    // and then will use m1 and m2 here as well
  })
})

Why can't we just have one require structure? I want to understand the motivation between this setup.

Upvotes: 2

Views: 1433

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44589

Nested require isn't mandatory, and can easily be avoided if this don't fit your style.

Although, this can be useful to load submodules or conditional modules (like a polyfill).

In a more personal experience, I often use nested require inside my router controller in order to load certain page view when they're requested. This allow me to request only the dependencies of my router without loading the entire page collection of an app.

I also often find myself using nested require to manage some i18n aspect of some apps by loading conditional locale.

Last thing, I'd just remember that modules should be defined using define, not require. require function is really used to arbitrary load scripts if needed (and can be use once to bootstrap your app). So in most of the real use case, you'll have some nested require inside a define module definition.

Hope this help!

Upvotes: 4

Related Questions