requirejs, almond:一个用almond构建的独立模块会加载所有依赖项,但不会执行主代码

requirejs, almond: A stand alone module built with almond loads all dependencies, but the main code is not executed

本文关键字:almond 依赖 加载 代码 执行 独立 一个 requirejs 构建 模块      更新时间:2023-09-26

我试图用杏仁建立一个独立的模块,这是我的设置。问题在下面。

缩写目录结构为:

|-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'
    },
],

UPDATE (add 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文件包含所有必要的部分,它不应该有所不同。

尝试将定义类更改为require类:

require( ["jquery", "fancybox", "app/messages"], function ($, fancybox, messages) {
    //all myApp's code here
    console.log('Is this thing on?')
});

放置包含您的require的文件。在使用require的任何其他文件之上的头部配置。然后确保包含新require函数的文件在HTML中以供引用。

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