CoffeeScript对象语法:exports.index vs exports = {}

时间:2012-06-23 01:16:11

标签: coffeescript express

我找到了

exports.index = (req, res) ->
  res.render "index",
    title: "Hello"

编译到

exports.index = function(req, res) {
    return res.render("index", { title: "Hello" })
}

适用于ExpressJS的东西。但是,我认为我可以使用:

exports = 
    index: (req, res) ->
        res.render "index",
            title: "Hello"

这样我就不必为所有路由键入exports.xxx,但是编译为

var exports;
exports = {
  index: function(req, res) {
    return res.render("index", {
      title: "Hello"
    });
  }
};

它似乎不适用于ExpressJS,为什么?

Error: In /labs/Projects/jiewmeng/routes/index.coffee, Parse error on line 1: Unexpected '{'
    at Object.parseError (/usr/lib/node_modules/coffee-script/lib/coffee-script/parser.js:477:11)
    at Object.parse (/usr/lib/node_modules/coffee-script/lib/coffee-script/parser.js:554:22)
    at /usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:43:20
    at Object..coffee (/usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:19:17)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Module.require (module.js:359:17)
    at require (module.js:375:17)
    at Object.<anonymous> (/labs/Projects/jiewmeng/server.coffee:6:12)
    at Object.<anonymous> (/labs/Projects/jiewmeng/server.coffee:74:4)

1 个答案:

答案 0 :(得分:3)

请参阅this answer explaining module.exports vs exports = foo vs exports.foo = bar

简而言之,如果将名为exports的局部变量分配给全新对象,则无法将属性分配给“真正的”exports对象,因此您的代码无法按预期工作。您可以A)将对象分配给module.exports或B)将属性分配给现有的exports对象。

在CoffeeScript中运行良好的一种模式是:

module.exports = {
  SomeClass
  someFunction
  someObject
}