繁体   English   中英

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

[英]Accessing global variables with node.js and CoffeeScript

我正在尝试为我正在使用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);

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

# 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

客户端和服务器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函数和browser <script>标记兼容。

更新:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM