require.js模块无法正确加载

时间:2012-03-20 13:59:24

标签: javascript requirejs

我有我的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按照它应该加载,并且它的依赖项被加载。它定义了回调函数,所有正确的依赖项都作为参数传递。不会抛出任何错误。但是,在bootstrap的回调中,App未定义!没有参数传递。是什么导致这个?这是我的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
        };
    }
);

5 个答案:

答案 0 :(得分:12)

据我所知,您应该只在您的app.js定义方法中删除'app'字符串。

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

答案 1 :(得分:5)

好的,我有同样的问题,关键是你定义的jquery路径别名。事实证明,RequireJS对jquery有一些特殊处理。如果你使用jquery模块名称,它会在那里做一些魔术。

根据你在jquery.min.js中所拥有的内容,它可能会导致一些问题,你可能还有一个jquery插件存在问题。以下是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());
        }
    }

对我来说,我有一个设置,以便我有一个名为/libs/jquery/jquery.js的文件,它返回jquery对象(只是RequireJS的包装器)。我最终做的只是将路径别名从jquery更改为$jquery。这有助于避免不受欢迎的魔法行为。

在我阅读的original tutorial中,他们使用的jQuery也有效。

答案 2 :(得分:3)

这是一个可以帮助您入门的简单示例:

我创建了一个非常简单的模块:

https://gist.github.com/c556b6c759b1a41dd99d

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

并在这个小提琴中使用它,只有jQuery作为额外的依赖:

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>

答案 3 :(得分:1)

这就是我用requirejs和backbone做的方式:

首先,使用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();
});

然后,我使用this syntax加载我的脚本。我发现通过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 () {
                        /* .... */
        }
    });
});

希望它有所帮助!

答案 4 :(得分:-2)

这有点晚了,但我刚遇到这个问题。我的解决方案可以在这里找到: https://stackoverflow.com/questions/27644844/can-a-return-statement-be-broken-across-multiple-lines-in-javascript

我出于不同的原因发布了这个问题,问我为什么我的修复工作首先起作用。 Elclanrs提供了完美的答案。长话短说,未定义可能是由于javascript的自动分号插入而出现的:Automatic semicolon insertion & return statements

如果您尝试将花括号的位置从下方更改为直接在return语句之后,我认为您的问题将会消失。

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

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