如何在JavaScript中有条件地要求文件

时间:2018-02-13 16:42:47

标签: javascript

我想根据变量有条件地要求/加载文件。我很难过,不知道怎么做。

这是我当前的文件:

function init() {
  return new Promise(resolve => {
    require({}, [
        'dojo/i18n!app/nls/app',
        //if (${lang} != "en") { `app/src/${lang}/culture` },
        'bridge/adobe/css/dribble.css',
        'builder/adobe/newcss/snip.css'
      ],
      function(f1, f2) {
        System.import('langUtils').then(langUtils => {
          langUtils.start(f1, f2);
          resolve();
        });
      });
  });
}

我如何根据条件(代码中的注释部分)要求文件。有人可以指出我正确的方向。

谢谢。

1 个答案:

答案 0 :(得分:1)

你已经有点了。 require的每个嵌套范围都提供了您所声明的依赖关系。您的外部作用域需要“app”,“dribble.css”和“snip.css”。您需要有另一个嵌套范围来说明“文化”要求。 “文化”将在该范围内定义(并且只在该范围内)。

请准备好Advanced AMD Usage: Conditionally requiring modules了解更多详情。

const lang = "en";

function init() {
    return new Promise(resolve => {
        require({}, [
            "dojo/i18n!app/nls/app"
            "bridge/adobe/css/dribble.css"
            "builder/adobe/newcss/snip.css"
        ], function (app, dribbleCSS, snipCSS) {
            if (lang !== "en") {
                require({}, [`app/src/${lang}/culture`], function (culture) {
                    console.log(culture);
                    /*
                     * This scope has culture and if your path needs culture,
                     * you need to execute next steps here, where culture is
                     * defined and available
                     */
                });
            }
            /*
             * culture is NOT available in this scope and you need to handle
             * appropriately by either duplicating this code above or doing
             * doing something else.
             */
            System.import("langUtils").then(langUtils => {
                langUtils.start(app);
                resolve();
            });
        });
    });
}