只是为了好玩,我要加载jquery
使用 require.js
.所以,我做了以下内容:
amd.js
define(["jquery-3.3.1"], function($) {
console.log(typeof $); // reports undefined
$("h1").html("Hello from AMD"); // causes TypeError (see below)
});
我的 HTML 文件非常简单,只有一个空白 <h1
> 元素和通常的 require.js
定义。
<script data-main = "amd" src = "require.js"></script>
此外,我的根文件夹(所有内容所在的位置)还包含 jquery-3.3.1.js
源文件。
您可能会看到整个示例代码 here on my github repo .忽略所有文件,除了:
- amd.html
- amd.js
- jquery-3.3.1.js
- require.js
但是,当我访问页面时,是否使用file:///
协议(protocol)或使用网络服务器,模块未加载,我看到一个空白页面。
控制台报告undefined
对于 console.log
语句,并报告我访问 jQuery
的第二条语句的以下异常对象/函数,它是从模块返回的内容。
TypeError: $ is not a function
我正在使用 jquery 版本 3.3.1。如果你看the source对于这个(和任何)版本的 jquery,众所周知 jquery 是一个函数对象。见下文:
来自 jQuery 源代码
define( [
...
], function( ..., ..., ... ) {
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
},
return jQuery;
});
最佳答案
您是否在 requirejs 配置中输入了“jquery”?
requirejs.config({
baseUrl: 'js/lib', // path to your source
paths: {
jquery: 'jquery-3.3.1' // invoke
}
});
关于javascript - 无法使用 require.js 加载 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872243/