Exact use of require() method.

You must Login before you can answer or comment on any questions.

Hi all, Can anybody tell me what is the exact use of the require() method and it's advantages when compared with the include() method.

Thanks in advance.

3 Answers

Accepted Answer

You should try to find more about CommonJS to understand what require is.

In short:

require allows you to load js modules. This modules are "encapsulated" so any variable you are defining inside is private. This way you keep the global namespace clean.

require will cache your module - the code is evaluated only once, the next time you need the module you already have it present, no need to read it again. This saves time in execution and memory.

include will push everything in the global namespace

include will be parsed and evaluated each time you use it.

— answered 11 months ago by Dan Tamas
answer permalink
1 Comment
  • Plus we want to deprecate Ti.include() in some future major release. It promotes bad practices and should not be used. :)

    — commented 11 months ago by Chris Barber

include() basically copy-pastes source code every time it's called. On the other hand, "require" parses module's source code just once and it returns same object that is exported every time it is called.

CommonJS specifies a require() function which lets one import the modules and then use them, the modules have a special global variable named exports which is an object which holds the things that will get exported.

You're asking all the right questions. Dan and Jakir both have good insight into the differences. Once you decide that you want to use require() (which you do want to use), have a look at these articles to learn a ton more about CommonJS and its use in Titanium.

Your Answer

Think you can help? Login to answer this question!