Requirejs: Load a module where the require('path/to/module') comes from a variable?

风流意气都作罢 提交于 2019-12-13 03:57:39

问题


Is it possible to do this:

 define( function( require ){
        var path = 'json!/app/pagelang/login';
        var appLang = require(path),

instead of this:

 define( function( require ){
        var appLang = require('json!/app/pagelang/login'),

from my tests it's not possible because it results on the following console error:

Uncaught Error: Module name "json!/app/pagelang/login_unnormalized2" has not been loaded yet for context: _


回答1:


Yes, you just have to change your syntax a little:

define( function( require ){
  var path = 'json!/app/pagelang/login';
  require([path], function(appLang){
    // Do stuff with appLang…
  });
});



回答2:


The answer is actually "no", your second snippet uses sugar syntax which uses regular expressions to rewrite your code "behind the scenes" to be something like:

define(['json!/app/pagelang/login'], function (appLang) {
  // appLang available
});

The same mechanism can't work when the module name is a variable because the dependencies block needs concrete module names, not variables. Because of that, as noted by @idbehold you need to use a proper asynchronous form of inlined require:

define(function (require) {
  var path = 'json!/app/pagelang/login';
  require([path], function (appLang) {
    // appLang available
  });
});


来源:https://stackoverflow.com/questions/23278249/requirejs-load-a-module-where-the-requirepath-to-module-comes-from-a-variab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!