Search code examples
javascriptrequirejssingle-page-applicationamd

How to properly configure requireJS


Hi I'm trying to make starting template for SPA project mainly using: RequireJS, KnockoutJS, TypeScript, etc.

I'm having hard time figuring out how to configure paths and folder structure for RequireJS to work properly...

here is my folder structure:

Scripts
 app
  components
   main.js
 lib
  knockout.js
  jquery.js

here is my RequireJS config file:

var config = {
    waitSeconds: 15,        
    paths: {
        app: '../app',
        'knockout': '/lib/knockout-3.4.2.',
        sammy: '/lib/sammy-0.7.5.',
        jquery: '../scripts/lib/jquery-1.10.2.'
    }
};

This is my attempt for main.js:

define(['jquery', 'PageOne', 'PageTwo'], function ($, pageOne, pageTwo) {
    $(document).ready(function () {

        var app = Sammy('#main', function () {

            this.get('#/pageOne', function () {
                pageOne.activate();
            });

            this.get('#/pageTwo', function () {
                pageTwo.activate();
            });

        });
        app.run();
    });
});

Here is my Index.cshtml script tag:

<script src="~/Scripts/lib/require.js" data-main="scripts/app/components/main"></script>

I saw in different project that config is called in header so this is in html header:

<script src="~/Scripts/app/config/require.config.js"></script>

My problem is that in main.js it looks for jquery under path defined in data-main (scripts/app/components/), but my jquery is in scripts/lib folder.

I'm trying to figure out by reading online the whole day but it's too much time for me I need someone to give me some hints how is this supposed to work?

Seriously having hard time figuring this out and RequireJS website just isn't helping me atm.

Note: I am beginner in JavaScript based projects, first SPA attempt, never used RequireJS...


Solution

  • Your configuration file does not do anything. I'm assuming from your description that the script element that loads it is located before the script element that loads RequireJS. That's one valid way to configure RequireJS, but if you want RequireJS to pick up the configuration, you need to set the global variable require before you load RequireJS, and RequireJS will use the value of require as its configuration. Right now you are setting config, which is ignored by RequireJS. So:

    var require = {
        waitSeconds: 15,    
        // etc...
    

    And once the configuration is in effect, you should be able to reduce your data-main to data-main="components/main".

    I see some of your paths in the paths configuration end with a dot. That's most likely a mistake on your part, or you have some very strange file names.