Getting error loading requirejs and jquery

I am trying a simple demo with requirejs and jquery for AMD. The following is the structure of the folder 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 this, I get an error: Uncaught TypeError: undefined is not a function in the line main.js 3.

What's wrong? I can not understand?

+7
source share
3 answers

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

Fixed main.js :

 define(['lib/jquery'], function () { $("#hello").html("Wow this works!"); }); 
+1
source

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

I understand that this is due to the way jquery defines itself. It uses the named define call:

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

So if you need 'lib/jquery' , this will not work. To do this, you need to specify 'jquery' exactly.

EDIT:

If you want to put jquery in the lib/ folder, and your base url will be the parent folder of lib/ ( lib/../ ), you can use a pad as follows:

 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 $ }); 
+4
source
 <script data-main="js" src="js/lib/require.js"></script> <script src="js/main.js"></script> 

- Is this what you want. the data-main attribute indicates only what should be the root of the relative query for it. Thus, you will need to upload the main file directly or through the script tag or call require() in the built-in script block

0
source

All Articles