使用Require.js动态加载模块 [英] Load modules dynamically with Require.js

查看:407
本文介绍了使用Require.js动态加载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照本文开头所述动态加载模块:

I am trying to load modules dynamically as described at the beginning of this post:

参考链接

这是我的scripts/main.js

require.config({
  baseUrl: 'scripts',
  paths: {
    jquery: 'lib/jquery-2.0.3'
  },
  config: {
    'main': {
      modules: ['mod1', 'mod2', 'mod3']
    }
  }
});

require(function(require, exports, module) {
  console.log("Loading modules");
  require(module.config().modules);
});

加载main.js时,永远不会执行外部require函数内部的代码,也永远不会在控制台输出加载模块".阅读此链接上的AMD文档后,我看不到我在做什么错.动态加载数组中外部定义的模块的正确方法是什么?

When main.js gets loaded, code inside the outer require function never gets executed and "Loading modules" never gets printed to the console. Having read the AMD documentation at This link, I can't see what I am doing wrong. What is the proper way of dynamically loading modules defined externally in an array?

谢谢!

更新:

这是我现在拥有的:

// main.js
require.config({
  ...
  config: {
    'some_module': {
      modules: ['mod1']
    }
  }
});

require(['some_module'], function(some_module) {
});

// some_module.js
define(function(require, exports, module) {
  var mods = module.config().modules;

  var mod;
  for (var i=0; i < mods.length; i++) {
    mod = require(mods[i]);
    mod.fn_call();
  }
});

执行require(module.config().modules)时,确实会加载mod1.我不确定如何使用require的返回值来调用由mod1返回的函数.

When I execute require(module.config().modules), mod1 indeed gets loaded. I am not sure how to use the return value of require to call a function returned by mod1, however.

使用上面的代码,我得到

With the code above, I get

Uncaught Error: Module name "mod1" has not been loaded yet for context: _
http://requirejs.org/docs/errors.html#notloaded

如何从正在加载的模块访问功能?

How can I access the functions from the modules I am loading?

推荐答案

您应使用定义指令:

define(function(require, exports, module) {
    console.log("Loading modules");
    require(module.config().modules);
});

通过RequireJS配置的 config 属性,您可以为每个模块定义配置.然后,在模块定义中,您可以访问该配置,以加载依赖项.

By config property of RequireJS configuration you define configurations for each of your modules. Then, in module definition you may access that config, in your case to load dependencies.

无论如何,我认为您不需要将应用程序的主要入口点公开为AMD模块,因为这没有任何意义.应该是这样的:

In any case, I don't think you need to expose your application's main entry point as an AMD module, because it makes no sense. It should be like this:

// some_module.js (or path for some_module alias)
define(function(require, exports, module) {
    require(module.config().modules);
    ...
    return function () {};
});

// main.js
require.config({
  ...
  config: {
    'some_module': {
      modules: ['mod1', 'mod2', 'mod3']
    }
  }
});

require('some_module'); // loads some_module, mod1, mod2, mod3

这篇关于使用Require.js动态加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆