【问题标题】:Unable to load jquery using require.js无法使用 require.js 加载 jquery
【发布时间】:2018-10-18 10:43:37
【问题描述】:

只是为了好玩,我想使用require.js 加载jquery。所以,我做了以下:

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。忽略所有文件,除了:

  1. amd.html
  2. amd.js
  3. jquery-3.3.1.js
  4. require.js

但是,当我访问该页面时,无论是使用file:/// 协议还是使用网络服务器,模块都没有加载,我看到一个空白页面。

控制台为console.log 语句报告undefined,并为我访问jQuery 对象/函数的第二个语句报告以下异常,这是从模块返回的内容。

TypeError: $ 不是函数

我正在使用 jquery 版本 3.3.1。如果您查看此(和任何)jquery 版本的the source,则众所周知,jquery 是一个函数对象。见下文:

来自 jQuery 源代码

define( [
    ...
], function( ..., ..., ... ) {

    jQuery = function( selector, context ) {

        return new jQuery.fn.init( selector, context );
    },

    return jQuery;
});

【问题讨论】:

    标签: javascript requirejs amd


    【解决方案1】:

    您是否在 requirejs 配置中输入了“jquery”?

    requirejs.config({
        baseUrl: 'js/lib', // path to your source
        paths: {
            jquery: 'jquery-3.3.1' // invoke
        }
    });
    

    【讨论】:

    • 没有。我认为配置是可选的,只有在您想指定路径不在本地文件系统上的路径时才需要。例如当您想从 CDN 导入模块时。这是绝对需要的吗。你的意思是 require.js 没有配置就不能工作?
    • 没有你的权利,它只建议使用它的预期方式。但你的正确肯定没关系!
    • 还请注意,根据 requre.js 网页文档,它说 - // 这将不起作用 define(['lib/jquery'], function ($) {...});
    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2013-03-20
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多