繁体   English   中英

node.js module.export

[英]node.js module.export

我正在努力了解我在这里缺少什么:

FILE: Sprite.js
function Sprite() {
}

Sprite.prototype.move = function () {
}

module.exports = Sprite;

FILE: Ship.js
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

FILE: Server.js
var util    = require('util'),
io  = require('socket.io'),
Sprite  = require('./sprite.js'),
Ship    = require('./ship.js');

var boo = new Ship(Sprite);

在Node.js外部可以正常工作。 但是,在Node.js中,它将无法识别船文件中的Sprite。 我尝试在sprite文件的末尾使用module.export = Sprite,但没有成功。

干杯

像这样将Sprite导出到FILE:Sprite.js中:

function Sprite() {
}

Sprite.prototype.move = function () {
}
exports.Sprite = Sprite;

然后在FILE内部:Ship.js(这是您缺少的棘手部分),使用require要求Sprite是这样的:

var Sprite = require('/path/to/Sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

如果模块导出了smth,如果您想使用它,那么您需要要求它(在您尝试使用它的模块中,而不是在主模块中),对吗?nodejs还会如何知道? “船级”在哪里? 更多信息在这里


编辑,查看其工作原理(所有文件都必须位于同一目录中,否则您将需要更改require路径)

文件sprite.js:

var Sprite = function () {
}
Sprite.prototype.move = function () {
    console.log('move');
}
module.exports = Sprite;

文件ship.js:

var Sprite = require('./sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
    console.log('enable');
}

module.exports = Ship;

文件main.js:

var Ship = require('./ship');

var boo = new Ship();

boo.move();
boo.enable();

使用node main.js运行示例,您应该看到:

C:\testrequire>node main.js
move
enable

问题是您没有包含module.exports = Sprite; 在Sprite.js文件的末尾。 请注意,我写的是导出而不是导出,因此错字一定是问题所在。

暂无
暂无

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

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