swhite
swhite

Reputation: 497

RequireJS Passing Dependencies

Not sure if this has been asked already but I am just wondering if importing a dependency using RequireJS to one file and then importing that file to another means the second file has to import the same dependency as the first file.

example -

file A

define([
    'jquery'
],function($) {
    //jquery thing here
}

File B

define([
    'A'
],function(A) {
    // do some jquery thing here
}

or

define([
    'jquery','A'
],function($,A) {
    // do some jquery thing here
}

Upvotes: 0

Views: 228

Answers (2)

Louis
Louis

Reputation: 151511

It is good modularization practice to have each module list its own dependencies explicitly rather than silently depend on a module being loaded through an intermediary. So your module B should take the second form you suggested for it: define(['jquery', 'A'], function ($, A) {....

Now, strictly speaking, you could have B only require A and you would be able to use jQuery in B without B having an explicitly dependency on jQuery. This is doable because jQuery, even when it is loaded as an AMD module, by default leaks $ and jQuery into the global space just like it does when it is loaded outside RequireJS. However, it is not good practice. You should not rely on this though unless you have a substantial reason to do so and document it very verbosely.

Upvotes: 2

Luka
Luka

Reputation: 455

You will have to use the third option, because otherwise $ will be undefined in the module B. But this doesn't mean RequireJS will import jQuery twice internally, it will just pass you the $ variable.

define([
    'jquery','A'
],function($,A) {
    // $ was passed as a function argument.
}

Upvotes: -1

Related Questions