简体   繁体   中英

requirejs can't see jquery

I have a simpliest project using requirejs. A data-main file is js/default.js

在此输入图像描述

You can see there two jQuery files. RequireJS can see only that which is located on the same level that default.js So this code:

require(
    ['jquery', 'modules/module1', 'modules/module2'],
    function($, Module1, Module2){
        $('body')
            .append(Module1.phrase)
            .append('<hr/>')
            .append(Module2.ask);
    }
);

...works

But if I change ['jquery', ... to ['libs/jquery', ... , it reveals an error:

Uncaught TypeError: $ is not a function

What's wrong here? Whole code is here: http://plnkr.co/edit/QuFsKN597RD873MOlUw8?p=preview

jQuery must indeed be required as jquery .

Now, there may be still confusion regarding the module name. Someone may look at the dependency libs/jquery and infer that jQuery is in fact required as jquery . That is, doing require(['libs/jquery'], ... would be asking RequireJS to load the module jquery located in libs/ . However, this is not the case . The module name of the module being required is the entire name listed in the dependency list. So in the require call above, the module name of the module required is libs/jquery . But jQuery calls define('jquery', ... to declare itself to RequireJS. The module name (the first argument is jquery , not libs/jquery and thus RequireJS fails to find the module requested.

A trivial fix is to add a paths configuration:

paths: {
    jquery: 'libs/jquery'
}

Please have a look at the requirejs docs:

jQuery defines named AMD module 'jquery' (all lower case) when it detects AMD/RequireJS. To reduce confusion, we recommend using 'jquery' as the module name in your requirejs.config.

http://requirejs.org/docs/jquery.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM