Just for fun, I want to load jquery
using require.js
. So, I made the following:
amd.js
define(["jquery-3.3.1"], function($) {
console.log(typeof $); // reports undefined
$("h1").html("Hello from AMD"); // causes TypeError (see below)
});
My HTML file is really simple and just has a blank <h1
> element and the usual require.js
definition.
<script data-main = "amd" src = "require.js"></script>
Also, my root folder, where everything is, also contains the jquery-3.3.1.js
source file.
You may see the whole example code here on my github repo. Ignore all files except:
However, when I access the page, whether using the file:///
protocol or using a web server, the module is not loaded and I see a blank page.
The console reports undefined
for the console.log
statement, and reports the following exception for the second statement where I access the jQuery
object/function, and it is what gets returned from the module.
TypeError: $ is not a function
I am using jquery version 3.3.1. If you look at the source of this (and any) version of jquery, it is well known that jquery is a function object. See below:
From the jQuery source
define( [
...
], function( ..., ..., ... ) {
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
},
return jQuery;
});
Did you enter 'jquery' into your requirejs config?
requirejs.config({
baseUrl: 'js/lib', // path to your source
paths: {
jquery: 'jquery-3.3.1' // invoke
}
});