Sander
Sander

Reputation: 13421

requirejs unable to find module returning undefined

i've been working with require before, but never ran into this issue, maybe i got a path wrong somewhere but this is my filestructure:

js
├───main.js
│
├───app
│   ├───app.js
│   ├───hello.js
│   ├───world.js
│   │
│   └───models
│       └───game.js
│
└───vendor
    ├───jquery.js
    └───require.js

main.js

require.config({
    paths: {
        'jquery':   '../js/vendor/jquery'
    },
    shim: {
        'jquery': {
            exports: '$'
        }
    }
});

require(['app/app', 'jquery', 'app/models/game'], function (App, $, Game) {
    console.log(arguments);
    $(function () {
        console.log('why is my App undefined?', App);
        App.init();

    });
});

app/app.js

define('App', ['hello', 'world'], function (hello, world) {

    var App = {};

    App.init = function () {
        alert(hello + ' ' + world);
    };

    return App;
});

the code fires alright, however my dependencies seem to fail on app or hello or world module, App logs as undefined, so does my game module.

app/app should be the right path to my App module or am I thinking that wrong?

Update

I thought the capital A for App fixed the issue (but at the same time I took a swing at Jlange's comment, so I fired up the app/App module from the index.html. Which seemed ok, but after continuing the development it came up again.

I can load every module in the same directory just fine, but I cannot modules from subdirectories.

like the initial example couldn't load app/App from within the Main module, so can the app/App module not import the models/Game module.

I literally have no clue what this can be, as I said before, I have worked with requirejs and have not run into this issue.

Update 2 I can make it work if I drop all the named modules,

define([dependencies], function (dependencies) {});

that works fine but as soon as I change it into a named module I cannot find it

define("moduleA", ['subdir/moduleB'], function (moduleB) {
    console.log(moduleB); // >> undefined
});
define("subdir/moduleB", [dependencies], function (dependencies) { return 'B'; });

Upvotes: 1

Views: 4420

Answers (1)

Sander
Sander

Reputation: 13421

edited

after many tries, to fix the above code, and reading up in the requirejs help pages, I found a small passage, saying it is best not to use named modules and let the optimizer name them for you.

So I decided to remove all module names

moduleA.js

define(['subdir/moduleB'], function (moduleB) {
    console.log(moduleB); // >> 'B'
});

subdir/moduleB.js

define([dependencies], function (dependencies) { return 'B'; });

this works just fine... don't know how I got fixed on using those moduleNames, Thought it would be better to name your modules.

Upvotes: 2

Related Questions