使用node.js和CoffeeScript访问全局变量

时间:2013-03-19 10:42:00

标签: javascript node.js coffeescript global-variables

我正在尝试为我正在使用Node.js和CoffeeScript编写的应用程序声明全局变量。所以我在一个公共文件中声明它,它在编译后连接到两个应用程序。在那个文件中我有例如:

root = exports ? this
root.myVariable = 300

所以我的第一个应用程序是HTML。当我尝试访问此变量时,例如通过

console.log myVariable

没有问题。但我的其他应用程序是由node命令启动的服务器应用程序,我无法访问该应用程序中的该变量。我试过了:

console.log root.myVariable
console.log myVariable

第一行我打印'未定义'(因此它看起来定义了root),而第二行,我得到了ReferenceError - myVariable未定义。

那么如何访问这个变量?

以下是Javascript中的输出代码,我想这可能会有所帮助:

(function() {
  var root, _ref;

  root = (_ref = typeof module !== "undefined" && module !== null ? module.exports : void 0) != null ? _ref : this;

  root.myVariable = 300;

}).call(this);

(function() {

  console.log(root.myVariable);

  console.log(myVariable);

}).call(this);

2 个答案:

答案 0 :(得分:2)

你很亲密,但你需要稍微改变一下

# config.coffee
module.exports =
  foo: "bar"
  hello: "world"
  db:
    user: naomik
    pass: password1

# lib/a.coffee
config = require "../config"

# lib/b.coffee
config = require "../config"

# lib/db.coffee
dbconfig = require("../config").db

答案 1 :(得分:0)

客户端和服务器JavaScript(或CoffeeScript)的工作方式不同。因此,编写一个可以在两个应用程序中运行的模块真的很难。

有许多库可以解决此问题,例如RequireJSBrowserify

但我对你的问题有两个更简单的建议。


首先,使用JSON来存储全局常量。在服务器端,您只需require JSON文件:

root = require './config.json'

在客户端,您可以手动解析或将其作为pjson投放。


我的第二个建议是编写一个非常简单的模块,它将与你的两个应用程序兼容。它看起来像这样:

root = 
  myVariable: 300
  myOtherVariable: 400

modulte.exports = root if module?.parent?

此代码应与node.js require功能和浏览器<script>标记兼容。

更新

我只是重读了你的问题并意识到,你几乎按照我的建议做了。但是你的代码看起来很好。您可以尝试使用module.export代替其别名exports,这可能会有所帮助:

root = modulte?.exports ? this
root.myVariable = 300

但是,正如我所说,你的代码对我来说也很好。

相关问题