javascript require.js 模块未正确加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9788288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:50:43  来源:igfitidea点击:

require.js modules not loading properly

javascriptrequirejs

提问by LordZardeck

I have my bootstrap file which defines the require.js paths, and loads the app and config modules.

我有我的引导文件,它定义了 require.js 路径,并加载了应用程序和配置模块。

// 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. 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! no arguments are passed. What can be causing this? Here's my app file ( modified for space)

app.js 像它应该的那样加载,并且它的依赖项被加载。它的定义回调被调用,所有正确的依赖项作为参数传递。不会抛出任何错误。但是,在引导程序的回调中, 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
        };
    }
);

回答by phawk

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){
    ...
);

回答by Michael Yagudaev

Ok I had the same problem, the key is the jquery path alias you define. It turns out that RequireJS has some special handling for jquery. If you use the jquery module name it will do a little bit of magic there.

好的,我遇到了同样的问题,关键是您定义的 jquery 路径别名。事实证明 RequireJS 对 jquery 有一些特殊的处理。如果您使用 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. Here are the relevant lines of code from the RequireJS source:

根据您在 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());
        }
    }

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). What I ended up doing was simply changing the path alias from jqueryto $jquery. This helps avoid the undesired magic behavior.

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

In the original tutorialI read they use jQuerywhich also works.

在我阅读的原始教程中,他们使用jQuery了也可以使用的教程

回答by Paul Grime

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>

回答by tmaximini

This is how I do it with requirejs and backbone:

这就是我使用 requirejs 和主干的方式:

first, define main or bootstrap file with config:

首先,使用配置定义主文件或引导文件:

// 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 syntaxto load my scripts. I find it easier than the array notation to just define my depencies via vardeclarations.

然后,我使用此语法加载我的脚本。我发现通过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!

希望能帮助到你!

回答by MingShun

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. To make a long story short, the undefined is probably appearing due to javascript's automatic semicolon insertion: Automatic semicolon insertion & return statements

我出于不同的原因发布了这个问题,首先要问为什么我的修复程序有效。Elclanrs提供了完美的答案。长话短说,undefined 可能是由于 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
        };
    }
);