【问题标题】:requirejs, almond: A stand alone module built with almond loads all dependencies, but the main code is not executedrequirejs, almond:用almond构建的独立模块,加载所有依赖,但不执行主代码
【发布时间】:2014-03-14 21:38:50
【问题描述】:

我正在尝试用杏仁构建一个独立的模块,这是我的设置。问题在底部。

缩写目录结构为:

|-static
   |-core
      |-js
        |-require.js
        |-almond.js
        |-common.js
        |-app.build.js
        |-app
          |-myApp.js

   |-vendor
      |-js
        |-jquery.js
        |-bootstrap.js
        |-fancybox.js

common.js 的缩写内容:

require.config({
    baseUrl: "/static/core/js",
    paths: {
        'jquery':'../../vendor/jquery/1.7.2/jquery',
        'bootstrap':'../../vendor/bootstrap/2.2.2/js/bootstrap',
        'fancybox':'../../vendor/fancybox/2.0.6/jquery.fancybox',
    },
    shim: {
        'bootstrap':['jquery'],
        'fancybox': ['jquery'],
        'app/messages': ["jquery"],
    },
    waitSeconds: 12
});

app/myApp.js 的缩写内容(是的,我知道我正在污染全球命名空间):

define(function (require) {
    var $ = require('jquery');
    require('fancybox');
    require('app/messages');

    //all myApp's code here
    console.log('Is this thing on?')
});

我的构建文件:app.build.js:

mainConfigFile: 'common.js',
removeCombined: true,
skipDirOptimize: true,
wrapShim: false,
wrap: false,

modules: [
    {
        name: 'almond',
        include: ['app/myApp'],
        out: ['myApp.js'
    },

],

更新(添加 html): 我的 django 模板 HTML 的底部:

{% require_module 'myApp' %}

模板标签翻译为:

<script src="/static/core/js/myApp.js"></script>

当我执行构建时,我得到了带有杏仁的完整构建、所有 myApp 的依赖项以及所有 myApp 的代码。但是,依赖项加载并执行它们的代码,但 myApp 的代码不执行。

我希望在 myApp 的依赖项加载后,我会看到“这东西在吗?” (参见上面的 app/myApp.js)在控制台中,但没有骰子...

注意:我实际上是使用 django-require 来构建独立模块,但我认为 app.build.js 非常接近它正在做的事情,并且考虑到最终的 myApp.js 文件包含所有必要的部分应该没什么区别。

【问题讨论】:

  • 你能告诉我们加载整个内容的 HTML 吗?
  • @Louis 我已经添加了 html
  • common.js 是否包含在 r.js 生成的最终包中?
  • 在这一点上不,我试图require(['common'],function('common'){..define callback..});但这导致文件中只有杏仁。我将尝试在回调中使用它。
  • @Louis 我尝试添加 common,但结果相同。

标签: javascript requirejs amd r.js


【解决方案1】:

尝试将您的定义类更改为要求类:

require( ["jquery", "fancybox", "app/messages"], function ($, fancybox, messages) {

    //all myApp's code here
    console.log('Is this thing on?')
});

将包含您的 require.config 的文件放在您使用 require 的任何其他文件之上。然后确保保存新 require 函数的文件在您的 HTML 中以供参考。

至少我过去就是这样使用 require 的。

【讨论】:

  • 我做的第一件事是使用您的 define() 版本,我得到了相同的结果。我也尝试将 require.config 放在 app/myApp.js 中,但同样没有区别。此外,所有依赖项都加载并执行,因此它不应该是配置问题。感谢您的建议。
  • 哎呀,我错过了你的意思。将定义更改为要求,现在尝试。
  • 谢谢!那成功了!知道为什么 require() 有效而 define() 无效吗?何时使用女巫似乎很随意。
  • 那是因为没有任何东西开始加载您的代码。 define定义一个模块。必须有一个显式或隐式的初始require。你可以在你给r.js的构建配置中使用insertRequire。它需要一组模块名称。只需将您的主模块放在那里就可以执行 QBM5 建议的相同操作。
  • @Louis 有道理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 2017-06-01
相关资源
最近更新 更多