代码之家  ›  专栏  ›  技术社区  ›  Mathieu

node/webpack/javascript es6-在require inside对象上添加条件。assign())

  •  0
  • Mathieu  · 技术社区  · 6 年前

    我有一个模块,通过要求正确的索引来设置语言。i18n.js

    下面的代码对于使用/fr/、/en/、/es/…的路径(URL)很好地工作。

    module.exports = function (locals) {
      var route = global.RoutesPages.routes.find(r => r.url == locals.path);
      const language = locals.path.split('/')[1]; 
      return Promise.resolve(    
          locals.template(
          Object.assign(
            {},
            {           
              title:        route.title,
              type:         route.type
            },
    
           require(`../../i18n-build/index.${language}.js`)
    
          )
        )
      )
    
    };
    

    所以它需要 example.com/fr/cool 文件 i18n-build/index.fr.js ,它需要 example.com/en/cool 文件 i18n-build/index.en.js

    问题是我遇到了这样一个情况:URL是example.com/global,因此需求告诉我它找不到正确的文件,因为它试图要求 example.com/global/foo 文件 i18n-build/index.global.js 这是意料之中的,因为我不想这个文件,也不想。实际上,对于访问example.com/global的用户,我希望使用 i18n构建/index.en.js 将英语作为“全局”用户默认值

    我尝试在需求中使用一个条件,但生成失败:

    module.exports = function (locals) {
      var route = global.RoutesPages.routes.find(r => r.url == locals.path);
      const language = locals.path.split('/')[1];
      function isCountry() {
        //detect if language in uri is "global", 
        //i.e not a specific country
        if (language !== "global" ) {
          return true;
        }
      }
    
      return Promise.resolve(    
          locals.template(
          Object.assign(
            {},
            { 
              title:        route.title,
              type:         route.type
            },
    
            require( isCountry ? `../i18n-build/index.${language}.js` : `../i18n-build/index.en.js` )        
    
          )
        )
      )
    
    };
    

    当webpack使用/fr/为一个url构建文件时,它似乎破坏了以前的工作,我得到了错误:

    Cannot find module '../i18n-build/index.fr.js'
    

    整个构建都失败了。

    我觉得我写的不正确,但我不知道如何应用一个基本上是这样的条件:

    如果(是国家),要求 ../i18n-build/index.${language}.js 否则需要 ../i18n-build/index.en.js

    编辑

    在一些评论要求我测试各种需求之后,下面是构建的结果:

    • require( ../../i18n构建/索引。$语言.js ) =>建筑工程

    • 要求( ../../i18n构建/index.fr.js ) =>建筑工程

    • require( isCountry ? ../i18n构建/索引。$语言.js : ../i18n内部版本/index.en.js ) =>生成失败

    • 要求(是国家? ../i18n构建/index.fr.js : ../i18n内部版本/index.en.js ) =>生成失败

    • 要求(是国家? ../../i18n构建/index.fr.js : ../../i18n内部版本/index.en.js ) =>建造工程!!

    • 要求(是国家? ../../i18n构建/索引。$语言.js : ../../i18n内部版本/index.en.js ) =>生成失败

    最后一个问题是如何根据需要正确地创建条件,因为这两个文件都存在,我甚至没有在其中使用变量($language)。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Syed Kashan Ali    6 年前

    const language = locals.path.split('/')[1] == 'global' ? 'en' : locals.path.split('/')[1];
    

    require(`../../i18n-build/index.${language}.js`)
    
        2
  •  0
  •   Jayffe    6 年前

    ../

    require( isCountry ?`../../i18n-build/index.${language}.js`:`../../i18n-build/index.en.js`)