Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Error with loading of requirejs and jquery

I am trying a simple demo with requirejs and jquery for AMD. Following is my folder structure structure:

├── index.html
└── js
    ├── lib
    │   ├── jquery.js
    │   └── require.js
    └── main.js

in my index.html file i have the following content:

  <head>
    <script data-main="js/main" src="js/lib/require.js"></script>
  </head>

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

  </body>

and my main.js file looks like this:

define(['lib/jquery'], function ($) {

  $("#hello").html("Wow this works!");

});

But when i do, i get an error: Uncaught TypeError: undefined is not a function in main.js line 3.

What is wrong? I can't understand?

like image 777
whatf Avatar asked Oct 19 '12 23:10

whatf


2 Answers

Read this issue: https://github.com/jrburke/requirejs/issues/435

My understanding is this is because of how jquery defines itself. It is using a named define call:

define( "jquery", [], function () { return jQuery; } );

So now, if you require 'lib/jquery' it won't work. You have to exactly require 'jquery' for it to work.

EDIT:

If you want to put jquery in lib/ folder and your base url to be the parent folder of lib/ (lib/../) you can use a shim like this:

requirejs.config({
  baseUrl: 'js',
  shim: {
    'lib/backbone': {
      deps: ['lib/underscore', 'lib/jquery'],
      exports: 'Backbone'
    },
    'lib/underscore': {
      exports: '_'
    },
    'lib/jquery': {
      exports: '$'
    }
  }
});

requirejs(['lib/jquery'], function($) {
  // use $
});
like image 141
Behrang Avatar answered Nov 13 '22 06:11

Behrang


I have tried your example without "$" in first line of main.js and it worked properly.

Fixed main.js:

define(['lib/jquery'], function () {
     $("#hello").html("Wow this works!");
});
like image 1
roomcays Avatar answered Nov 13 '22 05:11

roomcays