Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use IIFE with RequireJS

It seems to be that if you are using RequireJS and you use define and require, then there is not point of using IIFE as well, since each module is already wrapped in a define/require. Is that the case?

In other words, does this code

define(['app'], function(app)
{
    app.run();
});

has any difference/advantage to

(function() { 

    define(['app'], function(app) 
    {
        app.run();
    });

})();
like image 646
Kousha Avatar asked Sep 30 '22 09:09

Kousha


2 Answers

Generally, you don't need to use an IIFE with RequireJS but sometimes you should.

If you use the usual define([... deps ...], function (...) {...}) format then you are only reading define from the global space and everything else you do is encapsulated inside the function you pass to define. With or without an IIFE, you can leak what you want to leak and keep private what you want to keep private.

The IIFE will typically be desirable if you are writing code that you want to be able to run with and without RequireJS. For instance, this:

(function () {
    'use strict';
    function factory () {

        // Build our module...

        return something;
    }

    if (typeof define === 'function' && define.amd)
        define([], factory); // AMD environment: call define.
    else
        window.Foo = factory(); // Otherwise, leak into the global space.
})();

Popular libraries (e.g. jQuery) often have code like this that allows using them with RequireJS (or another AMD loader) and with script elements. This is extremely common. Using the IIFE allows to keep the factory function out of the global space.

like image 149
Louis Avatar answered Oct 03 '22 00:10

Louis


The define() function is in Global scope anyway, so calling it inside an IIFE doesn't make a difference at all and it's kind of redundant.

It would be different if you put code outside of the define callback but you shouldn't do that because each file should represent an encapsulated module.

The only time I can think of using an IIFE with RequireJS might be when I'm configuring my application by calling require.config() before initialization; but even then if I'm just calling require.config() and don't have any code on the outside, I still wouldn't use an IIFE.

In this example here there wasn't a need to use an IIFE: https://github.com/vasilionjea/bower-requirejs-starter/blob/master/local/js/main.js

I hope that answers your question.

like image 33
istos Avatar answered Oct 03 '22 02:10

istos