简体   繁体   English

require.js模块无法正确加载

[英]require.js modules not loading properly

I have my bootstrap file which defines the require.js paths, and loads the app and config modules. 我有我的bootstrap文件,它定义了require.js路径,并加载了app和config模块。

// Filename: bootstrap

// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.
require.config({
    paths: {
        bfwd: 'com/bfwd',
        plugins: 'jquery/plugins',
        ui: 'jquery/ui',
        jquery: 'jquery/jquery.min',
        'jquery-ui': 'jquery/jquery-ui.min',
        backbone: 'core/backbone.min',
        underscore: 'core/underscore.min'
    }
});
console.log('loading bootstrap');
require([
    // Load our app module and pass it to our definition function
    'app',
    'config'
], function(App){
    // The "app" dependency is passed in as "App"
    // Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
    console.log('initializing app');
    App.initialize();
});

app.js is loaded like it should, and it's dependencies are loaded. app.js像它应该加载,并且它的依赖项被加载。 it's define callback is called, with all the correct dependencies passed as arguments. 它定义了回调函数,所有正确的依赖项都作为参数传递。 No error is thrown. 不会抛出任何错误。 HOWEVER, in the bootstrap's callback, App is undefined! 但是,在bootstrap的回调中,App未定义! no arguments are passed. 没有参数传递。 What can be causing this? 是什么导致这个? Here's my app file ( modified for space) 这是我的app文件(为空间修改)

// Filename: app.js
define(
    'app',
    [
        'jquery',
        'underscore',
        'backbone',
        'jquery-ui',
        'bfwd/core',
        'plugins/jquery.VistaProgressBar-0.6'
    ], 
    function($, _, Backbone){
        var initialize = function()
        {
            //initialize code here
        }
        return 
        {
            initialize: initialize
        };
    }
);

As far as I am aware you should probably just drop the 'app' string in your app.js define method. 据我所知,您应该只在您的app.js定义方法中删除'app'字符串。

// Filename: app.js
define([
    'jquery',
    'underscore',
    'backbone',
    'jquery-ui',
    'bfwd/core',
    'plugins/jquery.VistaProgressBar-0.6'
], function($, _, Backbone){
    ...
);

Ok I had the same problem, the key is the jquery path alias you define. 好吧我遇到了同样的问题,关键是你定义的jquery路径别名。 It turns out that RequireJS has some special handling for jquery. 事实证明,RequireJS对jquery有一些特殊处理。 If you use the jquery module name it will do a little bit of magic there. 如果你使用jquery模块名称,它会在那里做一些魔术。

Depending on what you have in jquery.min.js it may cause some problems, also the jquery plugin you have there may be a problem. 根据你在jquery.min.js中的内容,它可能会导致一些问题,你的jquery插件也可能存在问题。 Here are the relevant lines of code from the RequireJS source: 以下是RequireJS源代码的相关代码行:

    if (fullName) {
        //If module already defined for context, or already loaded,
        //then leave. Also leave if jQuery is registering but it does
        //not match the desired version number in the config.
        if (fullName in defined || loaded[id] === true ||
            (fullName === "jquery" && config.jQuery &&
                config.jQuery !== callback().fn.jquery)) {
            return;
        }

        //Set specified/loaded here for modules that are also loaded
        //as part of a layer, where onScriptLoad is not fired
        //for those cases. Do this after the inline define and
        //dependency tracing is done.
        specified[id] = true;
        loaded[id] = true;

        //If module is jQuery set up delaying its dom ready listeners.
        if (fullName === "jquery" && callback) {
            jQueryCheck(callback());
        }
    }

For me I have it setup such that I have a file called /libs/jquery/jquery.js which returns the jquery object (just a wrapper for RequireJS). 对我来说,我有一个设置,我有一个名为/libs/jquery/jquery.js的文件,它返回jquery对象(只是RequireJS的包装器)。 What I ended up doing was simply changing the path alias from jquery to $jquery . 我最终做的只是将路径别名从jquery更改为$jquery This helps avoid the undesired magic behavior. 这有助于避免不受欢迎的魔术行为。

In the original tutorial I read they use jQuery which also works. 原始教程中,我读到他们使用jQuery也可以。

This is a simple example that might help get you started: 这是一个简单的示例,可能有助于您入门:

I've created a very simple module: 我创建了一个非常简单的模块:

https://gist.github.com/c556b6c759b1a41dd99d https://gist.github.com/c556b6c759b1a41dd99d

define([], function () {
  function my_alert (msg) {
    alert(msg);
  }
  return {
    "alert": my_alert
  };
});

And used it in this fiddle, with only jQuery as an extra dependency: 并在这个小提琴中使用它,只有jQuery作为额外的依赖:

http://jsfiddle.net/NjTgm/ http://jsfiddle.net/NjTgm/

<script src="http://requirejs.org/docs/release/1.0.7/minified/require.js"></script>
<script type="text/javascript">
  require.config({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min",
        "app": "https://gist.github.com/raw/c556b6c759b1a41dd99d/20d0084c9e767835446b46072536103bd5aa8c6b/gistfile1.js"
    },
    waitSeconds: 40
  });
</script>

<div id="message">hello</div>

<script type="text/javascript">
  require( ["jquery", "app"],
    function ($, app) {
      alert($.fn.jquery + "\n" + $("#message").text());
      app.alert("hello from app");
    }
  );
</script>

This is how I do it with requirejs and backbone: 这就是我用requirejs和backbone做的方式:

first, define main or bootstrap file with config: 首先,使用config定义main或bootstrap文件:

// bootstrap.js
require.config({
    paths: {
        text: 'lib/text',
        jQuery: 'lib/jquery-1.7.2.min',
        jqueryui: 'lib/jquery-ui-1.8.22.custom.min',
        Underscore: 'lib/underscore-1.3.3',
        Backbone: 'lib/backbone-0.9.2'
    },

    shim: {
        'Underscore': {
            exports: '_'
        },

        'jQuery': {
            exports: 'jQuery'
        },

        'jqueryui': {
            exports: 'jqueryui'
        },

        'Zepto': {
            exports: '$'
        },

        'Backbone': {
            deps: ['Underscore', 'Zepto'],
            exports: 'Backbone'
        }
});

define(function (require) {
    'use strict';

    var RootView = require('src/RootView');
    new RootView();
});

Then, I use this syntax to load my scripts. 然后,我使用此语法来加载我的脚本。 I find it easier than the array notation to just define my depencies via var declarations. 我发现通过var声明来定义我的依赖关系比使用数组符号更容易。

// rootview.js
define(function (require) {

    'use strict';

    var $ = require('Zepto'),
    Backbone = require('Backbone'),
    LoginView = require('./LoginView'),
    ApplicationView = require('./ApplicationView'),
    jQuery = require('jQuery').noConflict();



    return Backbone.View.extend({

        // append the view to the already created container
        el: $('.application-container'),

        initialize: function () {
            /* .... */
        },

        render: function () {
                        /* .... */
        }
    });
});

Hope it helps! 希望能帮助到你!

This is a bit late, but I just had this problem. 这有点晚了,但我刚遇到这个问题。 My solution can be found here: https://stackoverflow.com/questions/27644844/can-a-return-statement-be-broken-across-multiple-lines-in-javascript 我的解决方案可以在这里找到: https//stackoverflow.com/questions/27644844/can-a-return-statement-be-broken-across-multiple-lines-in-javascript

I posted that question for a different reason, to ask why my fix worked in the first place. 我出于不同的原因发布了这个问题,问我为什么我的修复工作首先起作用。 Elclanrs provided the perfect answer. Elclanrs提供了完美的答案。 To make a long story short, the undefined is probably appearing due to javascript's automatic semicolon insertion: Automatic semicolon insertion & return statements 长话短说,未定义可能是由于javascript的自动分号插入而出现: 自动分号插入和返回语句

If you try changing the position of the curly bracket from underneath to directly after the return statement, I think your problem will disappear. 如果您尝试从下面更改花括号的位置直接在return语句之后,我认为您的问题将消失。

// Filename: app.js
define(
.
.
.

    function($, _, Backbone){
        var initialize = function()
        {
            //initialize code here
        }
        return {
            initialize: initialize
        };
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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