包括类定义文件

时间:2012-07-22 00:34:35

标签: node.js

如何在server.js文件中包含一个包含类定义的文件?

我不想使用module.exports,因为我也希望在我的客户端javascript代码中使用此文件。

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您希望模块的内容在文件范围之外可用,则必须使用module.exports。使文件也可以在浏览器中运行只需要您额外执行if / else s

例如:

var self = {};

// Browser?
if(instanceof window !== 'undefined')
{
    window['my_module_name'] = self;
}
// Otherwise assume Node.js
else
{
    module.exports = self;
}

// Put the contents of this module in self
// For instance:
self.some_module_function = function() {
    // Do stuff
}

现在,如果你在Node.js中,你可以达到这样的功能:

my_module = require('my_module_name');
my_module.some_module_function(58);

或者如果你在浏览器中,你可以直接调用它,因为它是全局的:

my_module.some_module_function(58);

否则我可以推荐Stitch.js,它允许您使用CommonJS样式require和模块开发JavaScript代码,然后将其编译为也可以在浏览器中运行而不需要更改代码。

Require.js也允许此类功能。

这是关于在节点和浏览器中使用相同代码的另一个问题:
how to a use client js code in nodejs