javascriptrequirejsamdr.js

requirejs, almond: A stand alone module built with almond loads all dependencies, but the main code is not executed


I am trying to build a stand alone module with almond and this is my setup. The question is at the bottom.

Abbreviated directory structure is:

|-static
   |-core
      |-js
        |-require.js
        |-almond.js
        |-common.js
        |-app.build.js
        |-app
          |-myApp.js

   |-vendor
      |-js
        |-jquery.js
        |-bootstrap.js
        |-fancybox.js

Abbreviated contents of common.js:

require.config({
    baseUrl: "/static/core/js",
    paths: {
        'jquery':'../../vendor/jquery/1.7.2/jquery',
        'bootstrap':'../../vendor/bootstrap/2.2.2/js/bootstrap',
        'fancybox':'../../vendor/fancybox/2.0.6/jquery.fancybox',
    },
    shim: {
        'bootstrap':['jquery'],
        'fancybox': ['jquery'],
        'app/messages': ["jquery"],
    },
    waitSeconds: 12
});

Abbreviated contents of app/myApp.js (YES I KNOW I AM POLLUTING THE GLOBAL NAMESPACE):

define(function (require) {
    var $ = require('jquery');
    require('fancybox');
    require('app/messages');

    //all myApp's code here
    console.log('Is this thing on?')
});

My build file: app.build.js:

mainConfigFile: 'common.js',
removeCombined: true,
skipDirOptimize: true,
wrapShim: false,
wrap: false,

modules: [
    {
        name: 'almond',
        include: ['app/myApp'],
        out: ['myApp.js'
    },

],

UPDATE (added html): Bottom of my django template HTML:

{% require_module 'myApp' %}

The template tag translates to:

<script src="/static/core/js/myApp.js"></script>

When i execute the build i get the complete build with almond, all myApp's dependencies, and all of myApp's code. However, the dependencies load and execute their code, but myApp's code does not execute.

I would expect that after the myApp's dependencies load I would see "Is this thing on?" (see app/myApp.js above) in the console, but no dice...

NOTE: I am actually using django-require to build the stand alone module, but i think the app.build.js is fairly close to what it is doing and considering that the final myApp.js file contains all the necessary pieces it should not make a difference.


Solution

  • Try changing your define class to a require class:

    require( ["jquery", "fancybox", "app/messages"], function ($, fancybox, messages) {
    
        //all myApp's code here
        console.log('Is this thing on?')
    });
    

    Put the file containing your require.config in your head above any other files using require. Then make sure that the file holding your new require function is in your HTML for referencing.

    Thats how I have used require in the past at least.