【问题标题】:Sharing config between node app and client side javascript在节点应用程序和客户端 javascript 之间共享配置
【发布时间】:2018-04-27 03:58:47
【问题描述】:

我需要在节点应用程序和浏览器中都有一些配置对象。这是配置的路径和内容:

路径:[app]/public/js/config.js
内容:

var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}

在我的 html 中,我只是添加了一个脚本元素,它工作正常:

<script src="/js/config.js"></script>

然而,在节点应用程序中,我似乎没有导入对象并且我得到一个空对象:

var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}

我做错了什么?

【问题讨论】:

  • 您需要 config.js 中的 module.exports = 才能使 require 工作?
  • 为什么不使用标准的UMD 而不是上面的函数技巧?
  • @AnthonyKong,我在 config.js 中有 module.exports =
  • @ghybs,我会测试一下,看看它是否能解决这个问题。谢谢。

标签: javascript node.js


【解决方案1】:

您的isBrowser 变量被分配了一个函数,但它从未被执行。

因此它不执行任何环境检测。

【讨论】:

  • 谢谢!该部分是从this answer 借用(读取复制)的,但我错过了函数调用部分。将 if(!isBrowser) { 更改为 if(!isBrowser()) { 解决了该问题。
【解决方案2】:

代码应该是

if(!isBrowser()) {
    module.exports = config;
}

isBrowser 是这里的一个函数。因为在你的版本中!isBrowser 总是返回false 所以module.exports = config 永远不会被执行。

【讨论】:

    【解决方案3】:

    如果阻塞则替换

    if(!isBrowser) {
        module.exports = config;
    }
    

    if(!isBrowser()) {//this isBrowser() function
        module.exports = config;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多