简体   繁体   English

node.js module.export

[英]node.js module.export

I'm struggling to understand what I am missing here: 我正在努力了解我在这里缺少什么:

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);

Outside of Node.js this works fine. 在Node.js外部可以正常工作。 In Node.js however it won't recognise Sprite in the ship file. 但是,在Node.js中,它将无法识别船文件中的Sprite。 I've tried using module.export = Sprite at the end of the sprite file with no success. 我尝试在sprite文件的末尾使用module.export = Sprite,但没有成功。

Cheers 干杯

Export Sprite in FILE: Sprite.js like this : 像这样将Sprite导出到FILE:Sprite.js中:

function Sprite() {
}

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

Then inside FILE: Ship.js ( this is the tricky part you're missing ) use require to require the Sprite like this: 然后在FILE内部:Ship.js(这是您缺少的棘手部分),使用require要求Sprite是这样的:

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

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

If a module exports smth, if you whant to use it then you need to require it (in the module you're trying to play with it, not in the main module) don't you?, how else is nodejs going to know where the ship ''class'' is ? 如果模块导出了smth,如果您想使用它,那么您需要要求它(在您尝试使用它的模块中,而不是在主模块中),对吗?nodejs还会如何知道? “船级”在哪里? more info here 更多信息在这里


Edit, see this working ( all files need to be in the same directory or you'll need to change the require path ) 编辑,查看其工作原理(所有文件都必须位于同一目录中,否则您将需要更改require路径)

File sprite.js : 文件sprite.js:

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

File ship.js : 文件ship.js:

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

Ship.prototype = new Sprite();

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

module.exports = Ship;

File main.js : 文件main.js:

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

var boo = new Ship();

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

Run the example using node main.js and you should see : 使用node main.js运行示例,您应该看到:

C:\testrequire>node main.js
move
enable

The problem is you didn't include module.exports = Sprite; 问题是您没有包含module.exports = Sprite; at the end of the Sprite.js file. 在Sprite.js文件的末尾。 Note that I wrote exports and not export, so that typo must have been the problem. 请注意,我写的是导出而不是导出,因此错字一定是问题所在。

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

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