Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require.js modules not loading properly

I have my bootstrap file which defines the require.js paths, and loads the app and config modules.

// Filename: bootstrap

// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.
require.config({
    paths: {
        bfwd: 'com/bfwd',
        plugins: 'jquery/plugins',
        ui: 'jquery/ui',
        jquery: 'jquery/jquery.min',
        'jquery-ui': 'jquery/jquery-ui.min',
        backbone: 'core/backbone.min',
        underscore: 'core/underscore.min'
    }
});
console.log('loading bootstrap');
require([
    // Load our app module and pass it to our definition function
    'app',
    'config'
], function(App){
    // The "app" dependency is passed in as "App"
    // Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
    console.log('initializing app');
    App.initialize();
});

app.js is loaded like it should, and it's dependencies are loaded. it's define callback is called, with all the correct dependencies passed as arguments. No error is thrown. HOWEVER, in the bootstrap's callback, App is undefined! no arguments are passed. What can be causing this? Here's my app file ( modified for space)

// Filename: app.js
define(
    'app',
    [
        'jquery',
        'underscore',
        'backbone',
        'jquery-ui',
        'bfwd/core',
        'plugins/jquery.VistaProgressBar-0.6'
    ], 
    function($, _, Backbone){
        var initialize = function()
        {
            //initialize code here
        }
        return 
        {
            initialize: initialize
        };
    }
);
like image 917
LordZardeck Avatar asked Mar 20 '12 13:03

LordZardeck


People also ask

Why is require not working in JS?

This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.

What is require () in JavaScript?

require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.

Can I use require in JS file?

With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.

Can you use require in browser JS?

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.


3 Answers

As far as I am aware you should probably just drop the 'app' string in your app.js define method.

// Filename: app.js
define([
    'jquery',
    'underscore',
    'backbone',
    'jquery-ui',
    'bfwd/core',
    'plugins/jquery.VistaProgressBar-0.6'
], function($, _, Backbone){
    ...
);
like image 64
phawk Avatar answered Nov 11 '22 12:11

phawk


Ok I had the same problem, the key is the jquery path alias you define. It turns out that RequireJS has some special handling for jquery. If you use the jquery module name it will do a little bit of magic there.

Depending on what you have in jquery.min.js it may cause some problems, also the jquery plugin you have there may be a problem. Here are the relevant lines of code from the RequireJS source:

    if (fullName) {
        //If module already defined for context, or already loaded,
        //then leave. Also leave if jQuery is registering but it does
        //not match the desired version number in the config.
        if (fullName in defined || loaded[id] === true ||
            (fullName === "jquery" && config.jQuery &&
                config.jQuery !== callback().fn.jquery)) {
            return;
        }

        //Set specified/loaded here for modules that are also loaded
        //as part of a layer, where onScriptLoad is not fired
        //for those cases. Do this after the inline define and
        //dependency tracing is done.
        specified[id] = true;
        loaded[id] = true;

        //If module is jQuery set up delaying its dom ready listeners.
        if (fullName === "jquery" && callback) {
            jQueryCheck(callback());
        }
    }

For me I have it setup such that I have a file called /libs/jquery/jquery.js which returns the jquery object (just a wrapper for RequireJS). What I ended up doing was simply changing the path alias from jquery to $jquery. This helps avoid the undesired magic behavior.

In the original tutorial I read they use jQuery which also works.

like image 44
Michael Yagudaev Avatar answered Nov 11 '22 13:11

Michael Yagudaev


This is a simple example that might help get you started:

I've created a very simple module:

https://gist.github.com/c556b6c759b1a41dd99d

define([], function () {
  function my_alert (msg) {
    alert(msg);
  }
  return {
    "alert": my_alert
  };
});

And used it in this fiddle, with only jQuery as an extra dependency:

http://jsfiddle.net/NjTgm/

<script src="http://requirejs.org/docs/release/1.0.7/minified/require.js"></script>
<script type="text/javascript">
  require.config({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min",
        "app": "https://gist.github.com/raw/c556b6c759b1a41dd99d/20d0084c9e767835446b46072536103bd5aa8c6b/gistfile1.js"
    },
    waitSeconds: 40
  });
</script>

<div id="message">hello</div>

<script type="text/javascript">
  require( ["jquery", "app"],
    function ($, app) {
      alert($.fn.jquery + "\n" + $("#message").text());
      app.alert("hello from app");
    }
  );
</script>
like image 39
Paul Grime Avatar answered Nov 11 '22 11:11

Paul Grime