简体   繁体   中英

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. In Node.js however it won't recognise Sprite in the ship file. I've tried using module.export = Sprite at the end of the sprite file with no success.

Cheers

Export Sprite in FILE: Sprite.js like this :

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:

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

File sprite.js :

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

File 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 :

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

var boo = new Ship();

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

Run the example using node main.js and you should see :

C:\testrequire>node main.js
move
enable

The problem is you didn't include module.exports = Sprite; at the end of the Sprite.js file. Note that I wrote exports and not export, so that typo must have been the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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