节点/ Webpack / javascript es6-在Object.Assign()

时间:2018-07-27 09:07:54

标签: javascript node.js webpack

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

下面的代码适用于带有/ fr /,/ en /,/ es / ...的路径(网址)

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.jsexample.com/en/cool需要文件i18n-build/index.en.js

问题是我遇到一种情况,该URL为example.com/global,因此require告诉我找不到正确的文件,因为它试图要求example.com/global/foo的文件{{1} }这是可以预期的,因为我没有这个文件,也不想。确实,对于访问example.com/global的用户,我想使用i18n-build/index.global.js和英语作为“全局”用户默认值

我尝试在require中使用一个条件,但是构建失败:

i18n-build/index.en.js

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

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` )        

      )
    )
  )

};

整个构建失败。

我认为我的写法不正确,但我不知道如何应用基本上是这样的条件:

如果(isCountry),要求Cannot find module '../i18n-build/index.fr.js' ,否则要求../i18n-build/index.${language}.js

编辑

在要求我测试各种要求的评论之后,这里是构建结果:

  • ../i18n-build/index.en.js ../../ i18n-build / index。$ {language} .js require( =>构建作品

  • ) ../../ i18n-build / index.fr.js require( =>构建作品

  • ) ../ i18n-build / index。$ {language} .js require( isCountry ? ../ i18n-build / index.en.js : =>构建失败

  • ) ../ i18n-build / index.fr.js require( isCountry ? ../ i18n-build / index.en.js : =>构建失败< / p>

  • ) ../../ i18n-build / index.fr.js require( isCountry ? ../../ i18n-build / index.en.js {{1} } =>构建作品!

  • : ../../ i18n-build / index。$ {language} .js ) ../../ i18n-build / index.en.js { {1}} =>构建失败

最后一个确实表明了这个问题,因为这两个文件确实存在,如何在需求上正确创建条件,我什至没有在其中使用变量($ language)

2 个答案:

答案 0 :(得分:1)

通过以下方法更改您的语言分配行:

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

然后使用第一个代码 require

require(`../../i18n-build/index.${language}.js`)

答案 1 :(得分:0)

因此错误一定是拼写错误,请尝试在条件中再添加../

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