EzDevInfo.com

requirejs interview questions

Top requirejs frequently asked interview questions

When should I use require() and when to use define()?

I have being playing around with requirejs for the last few days. I am trying to understand the differences between define and require.

Define seems to allow for module separation and allow for dependency ordering to be adhere. But it downloads all the files it needs to begin with. Whilst require only loads what you need when you need it.

Can these two be used together and for what purposes should each of them be used?


Source: (StackOverflow)

Loading Backbone and Underscore using RequireJS

I'm trying to load Backbone and Underscore (as well as jQuery) with RequireJS. With the latest versions of Backbone and Underscore, it seems kind of tricky. For one, Underscore automatically registers itself as a module, but Backbone assumes Underscore is available globally. I should also note that Backbone doesn't seem to register itself as a module which makes it kind of inconsistent with the other libs. This is the best main.js I could come up with that works:

require(
{
    paths: {
        'backbone': 'libs/backbone/backbone-require',
        'templates': '../templates'
    }
},
[
    // jQuery registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js',

    // Underscore registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js'
], function() {

    // These nested require() calls are just due to how Backbone is built.  Underscore basically says if require()
    // is available then it will automatically register an "underscore" module, but it won't register underscore
    // as a global "_".  However, Backbone expects Underscore to be a global variable.  To make this work, we require
    // the Underscore module after it's been defined from within Underscore and set it as a global variable for
    // Backbone's sake.  Hopefully Backbone will soon be able to use the Underscore module directly instead of
    // assuming it's global.
    require(['underscore'], function(_) {
        window._ = _;
    });

    require([
        'order!http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js',
        'order!app'
    ], function(a, app) {
        app.initialize();
    })
});

I should mention that, while it works, the optimizer chokes on it. I receive the following:

Tracing dependencies for: main
js: "/home/httpd/aahardy/requirejs/r.js", line 7619: exception from uncaught JavaScript throw: Error: Error: Error evaluating module "undefined" at location "/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js":
JavaException: java.io.FileNotFoundException: /home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js (No such file or directory)
fileName:/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js
lineNumber: undefined
http://requirejs.org/docs/errors.html#defineerror
In module tree:
    main

Is there a better way of handling this? Thanks!


Source: (StackOverflow)

Advertisements

Requirejs why and when to use shim config

i read the requirejs document from here api

requirejs.config({
    shim: {
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'foo': {
            deps: ['bar'],
            exports: 'Foo',
            init: function (bar) {
                //Using a function allows you to call noConflict for
                //libraries that support it, and do other cleanup.
                //However, plugins for those libraries may still want
                //a global. "this" for the function will be the global
                //object. The dependencies will be passed in as
                //function arguments. If this function returns a value,
                //then that value is used as the module export value
                //instead of the object found via the 'exports' string.
                return this.Foo.noConflict();
            }
        }
    }
});

but i am not getting shim part of it. why should i use shim and how should i configure, can i get some more clarification

please can any one explain with example why and when should we use shim. thanks.


Source: (StackOverflow)

Best way to organize jQuery/JavaScript code (2013) [closed]

The Problem

This answer has been answered before but are old and not up to date. I have over 2000 lines of code in a single file, and as we all know this is bad practice, especially when i'm looking through code or adding new features. I want to better organize my code, for now and for the future.

I should mention that I'm building a tool (not a simple website) with lots of buttons, UI elements, drag, drops, action listeners/handlers and function in the global scope where several listeners may use the same function.

Example code

$('#button1').on('click', function(e){
    // Determined action.
    update_html();
});

... // Around 75 more of this

function update_html(){ .... }

...

More example code

Conclusion

I really need to organize this code for best use and not to repeat myself and be able to add new features and update old ones. I will be working on this by myself. Some selectors can be 100 lines of code others are 1. I have looked a bit at require.js and found it kinda repetitive, and actually writing more code than needed . I'm open to any possible solution that fit this criteria and link to resource / examples are always a plus.

Thanks.


Source: (StackOverflow)

Mismatched anonymous define() module

I'm getting this error when I browse my webapp for the first time (usually in a browser with disabled cache).

Error: Mismatched anonymous define() module: function (require) {

HTML:

<html>
   .
   .
   .
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
   <script> var require = { urlArgs: "v=0.4.1.32" }; </script>
   <script data-main="assets/js/main" src="assets/js/libs/require.js"></script>
   <script src="assets/js/ace/ace.js?v=0.4.1.32"></script>
   </body>
</html>

JS:

$(function () {
    define(function (require) {
        // do something
    });
});

Anyway know what exactly this error mean and why its happening?

source file, a short discussion about it in the github issues page


Source: (StackOverflow)

RequireJS: Difference between "requirejs" and "require" functions

I am using requireJS 2.x. I found out that some tutorials (and the official docs) sometimes use

requirejs.config({ [...] });
requirejs(["module"]) ...

and sometimes

require.config({ [...] });
require(["module"]) ...

Is there any difference between those two functions (require and requirejs)? I could not find any word about that in the docs. :(


Source: (StackOverflow)

How to load bootstrapped models in Backbone.js while using AMD (require.js)

Backbone.js documentation suggest loading bootstrapped models this way:

<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= @accounts.to_json %>);
var Projects = new Backbone.Collection;
Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>

But this is a pattern that can't be used in AMD approach (using require.js)

The only possible solution is to declare global variable storing JSON data and use this variable later in relevant initialize methods.

Is there a better way to do this (without globals)?


Source: (StackOverflow)

Using reactjs with requirejs

Recently, I started using reactjs along with a backbonejs router to build an application.

I usually use use requirejs for dependency and code management. But, problem arises when I try to include files that contain jsx syntax.

This is what I have so far as my router.js:

define(["backbone", "react"], function(Backbone, React) {

  var IndexComponent = React.createClass({
    render : function() {
      return (
        <div>
        Some Stuff goes here
        </div>
        );
    }
  });



  return Backbone.Router.extend({
    routes : {
      "": "index"
    },
    index : function() {
      React.renderComponent(<IndexComponent />, document.getElementById('index'));
    }
  });
});

How do I put IndexComponent in its own file and call it in this file ? I have tried the usual method (the same that I have used with backbone and react) but got an error due to jsx syntax.


Source: (StackOverflow)

Getting requirejs to work with Jasmine

I first want to say that I am new to RequireJS and even newer to Jasmine.

I am having some issues with the SpecRunner and require JS. I have been following the tutorials of Uzi Kilon and Ben Nadel (along with some others) and they helped some but I am still having some issues.

It seems that, if there is an error that is thrown in the test (I can think of one in particular, a type error) the spec runner html will display. This tells me that I have some issues in the javascript. However, after I fix those error no HTML is displayed anymore. I cannot get the test runner to display at all. Can someone find something wrong with my code that would cause this issue?

Here is my directory structure:

Root 
|-> lib
    |-> jasmine
        |-> lib (contains all of the jasmine lib)
        |-> spec
        |-> src
    |-> jquery (jquery js file)
    |-> require (require js file) 
index.html (spec runner) specRunner.js

Here is the SpecRunner (index) HTML:

<!doctype html>
<html lang="en">
    <head>
        <title>Javascript Tests</title>

        <link rel="stylesheet" rel='nofollow' href="lib/jasmine/lib/jasmine.css">

        <script src="lib/jasmine/lib/jasmine.js"></script>
        <script src="lib/jasmine/lib/jasmine-html.js"></script>
        <script src="lib/jquery/jquery.js"></script>
        <script data-main="specRunner" src="lib/require/require.js"></script>

        <script>
            require({ paths: { spec: "lib/jasmine/spec" } }, [
                    // Pull in all your modules containing unit tests here.
                    "spec/notepadSpec"
                ], function () {
                    jasmine.getEnv().addReporter(new jasmine.HtmlReporter());
                    jasmine.getEnv().execute();
                });
        </script>

    </head>

<body>
</body>
</html>

Here is the specRunner.js (config)

require.config({
    urlArgs: 'cb=' + Math.random(),
    paths: {
        jquery: 'lib/jquery',
        jasmine: 'lib/jasmine/lib/jasmine',
        'jasmine-html': 'lib/jasmine/lib/jasmine-html',
        spec: 'lib/jasmine/spec/'
    },
    shim: {
        jasmine: {
            exports: 'jasmine'
        },
        'jasmine-html': {
            deps: ['jasmine'],
            exports: 'jasmine'
        }
    }
});

Here is a spec:

require(["../lib/jasmine/src/notepad"], function (notepad) {
    describe("returns titles", function() {
        expect(notepad.noteTitles()).toEqual("");


    });
});

The notepad source:

define(['lib/jasmine/src/note'], function (note) {

    var notes = [
        new note('pick up the kids', 'dont forget to pick  up the kids'),
        new note('get milk', 'we need two gallons of milk')
    ];


    return {
        noteTitles: function () {
            var val;

            for (var i = 0, ii = notes.length; i < ii; i++) {
                //alert(notes[i].title);
                val += notes[i].title + ' ';
            }

            return val;
        }
    };
});

And the Note source (JIC):

define(function (){
    var note = function(title, content) {
        this.title = title;
        this.content = content;
    };

    return note;
});

I have made sure that, as far as the app is concerned, the paths are correct. Once I get this working I can play with configuring that paths so that it isn't so yucky.


Source: (StackOverflow)

How to achieve lazy loading with RequireJS?

We're building a non-trival web application using Backbone, RequireJS and Handlebars, and well, I'm just curious. At the moment, each of our models sorta looks like this:

define(['Backbone', 'js/thing/a', 'js/thing/b', 'js/lib/bob'], function(a, b, bob) {
  return Backbone.Router.extend({
    // stuff here
  });
});

where thing/a, thing/b both have their own dependencies, for example on Handlebars templates, etc. What happens now is that in my main.js, all of the 'top-level' routers are loaded and initialized; each top-level router has a set of dependencies (models, views, etc) which each have their own dependencies (templates, helpers, utils, etc). Basically, a big tree structure.

The problem in this case is that this entire tree is resolved and loaded on page load. I don't mind that per sé, as we'll run it through the optimizer eventually and end up with one big single file (reducing RequireJS to basically a modularization framework). However, I am curious whether you can load stuff like views and templates 'on demand'.

There is the "simplified CommonJS wrapping" explained here, so I tried that:

define(function(require) {
  Backbone = require('Backbone');
  return Backbone.Router.extend({
    doStuff: function() {
      var MyView = require('js/myView');
      new MyView().render();
    }
  });
});

However, looking at Chrome's network inspector, it seems that RequireJS - somehow, even without triggering the route that triggers the doStuff handler - still loads the myView dependency. Questions:

  • Is this actually possible? Are there black magicks in RequireJS that looks for calls to require() without actually triggering the doStuff route?
  • Is this the theoretically correct way of going about 'on-demand', lazy loading of RequireJS modules and resources?
  • Does the r.js optimizer still work as advertised if you use this notation?

Source: (StackOverflow)

RequireJS: How to define modules that contain a single "class"?

I have a number of JavaScript "classes" each implemented in its own JavaScript file. For development those files are loaded individually, and for production they are concatenated, but in both cases I have to manually define a loading order, making sure that B comes after A if B uses A. I am planning to use RequireJS as an implementation of CommonJS Modules/AsynchronousDefinition to solve this problem for me automatically.

Is there a better way to do this than to define modules that each export one class? If not, how to you name what the module exports? A module "employee" exporting a class "Employee", as in the example below, doesn't feel DRY enough to me.

define("employee", ["exports"], function(exports) {
    exports.Employee = function(first, last) {
        this.first = first;
        this.last = last;
    };
});

define("main", ["employee"], function (employee) {
    var john = new employee.Employee("John", "Smith");
});

Source: (StackOverflow)

When to use Requirejs and when to use bundled javascript?

This may be a dumb question for web guys. But I am a little confused over this. Now, I have an application where I am using a couple of Javascript files to perform different tasks. Now, I am using Javascript bundler to combine and minify all the files. So, at runtime there will be only one app.min.js file. Now, Requirejs is used to load modules or files at runtime. So, the question is if I already have all things in one file, then do I need requirejs? Or what is a use case scenario where I can use requirejs and/or bundler?

Please let me know if any further details are needed.


Source: (StackOverflow)

RequireJS: Loading modules including templates and CSS [closed]

After playing around with AMD/RequireJS I was wondering if it is a good idea to load UI modules including templates and CSS so they are completely independent from the web page.

It sounds like good, but I haven't seen this implemented in the wild so there may be pitfalls.

Think of some UI module with the following structure:

myWidget
    |--img 
    |--main.js
    |--styles.css
    +--template.tpl

All stuff in one folder. Looks very nice.

The module in main.js would look something like this:

define(["TemplateEngine", "text!myWidget/template.tpl"], function(TemplateEngine, template) {

    // Load CSS (Pseudo Code)
    var cssUrl = "myWidget/styles.css";
    appendToHead(cssUrl);

    return function() {
        return {
            render: function(data) {
                  return TemplateEngine.toHtml(template, data);
            } 
        }
    }
});

Questions are now:

  1. Am I missing something?
  2. Are there any plugins/concepts how to achieve this in a "standard" way?
  3. Is the RequireJS optimizer able to handle the CSS part here, say concat/minify the stylesheets like it does with the JS parts?
  4. Any opinions on that? Good or bad?

Source: (StackOverflow)

Understanding when and how to use Require.JS

I've just begun to work with Require.JS and I'm a bit unclear on the appropriate cases in which it should be used, as well as the correct way to use it in those cases.

Here's how I currently have things set up with Require.JS. I have two functions, functionA() and functionB(). Both of these functions require an additional function, functionC() to work properly.

I only want to load functionC() when necessary, i.e. when functionA() or functionB() is going to be called. So I have the following files:

functionC.js

functionC(){
  //do stuff
}

functionA.js

functionA(){  
  define(['functionC'],function(){
    //functionC() is loaded because it is listed as a dependency, so we can proceed
    //do some functionA() stuff
  });
}

functionB.js

functionB(){  
  define(['functionC'],function(){
    //functionC() is loaded because it is listed as a dependency, so we can proceed
    //do some functionB() stuff
  });
}

So, is this set up correctly? And if I end up calling both functionA() and functionB() on the same page, is extra work being done since they both load the functionC.js file? If so, is that a problem? And if so, is there a way to set it up so that they first check to see if functionC.js has been loaded yet, and only load it if it hasn't been? Finally, is this an appropriate use of Require.JS?


Source: (StackOverflow)

How to handle circular dependencies with RequireJS/AMD?

In my system, I have a number of "classes" loaded in the browser each a separate files during development, and concatenated together for production. As they are loaded, they initialize a property on a global object, here G, as in this example:

var G = {};

G.Employee = function(name) {
    this.name = name;
    this.company = new G.Company(name + "'s own company");
};

G.Company = function(name) {
    this.name = name;
    this.employees = [];
};
G.Company.prototype.addEmployee = function(name) {
    var employee = new G.Employee(name);
    this.employees.push(employee);
    employee.company = this;
};

var john = new G.Employee("John");
var bigCorp = new G.Company("Big Corp");
bigCorp.addEmployee("Mary");

Instead of using my own global object, I am considering to make each class its own AMD module, based on James Burke's suggestion:

define("Employee", ["Company"], function(Company) {
    return function (name) {
        this.name = name;
        this.company = new Company(name + "'s own company");
    };
});
define("Company", ["Employee"], function(Employee) {
    function Company(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    return Company;
});
define("main", ["Employee", "Company"], function (Employee, Company) {
    var john = new Employee("John");
    var bigCorp = new Company("Big Corp");
    bigCorp.addEmployee("Mary");
});

The issue is that before, there was no declare-time dependency between Employee and Company: you could put the declaration in whatever order you wanted, but now, using RequireJS, this introduces a dependency, which is here (intentionally) circular, so the above code fails. Of course, in addEmployee(), adding a first line var Employee = require("Employee"); would make it work, but I see this solution as inferior to not using RequireJS/AMD as it requires me, the developer, to be aware of this newly created circular dependency and do something about it.

Is there a better way to solve this problem with RequireJS/AMD, or am I using RequireJS/AMD for something it was not designed for?


Source: (StackOverflow)