EdSilva
EdSilva

Reputation: 35

How to use module.exports and requireJS?

im quite a noob in html and js, so forgive me if this is a dumb question but, im trying to use requireJs to export modules in node and i can't get the function work right. here is the code extracted from example.

first i have this main.js, as the note in the documentation says http://requirejs.org/docs/node.html#2

var sayHi = require(['./greetings.js'], function(){}); 
console.log(sayHi);

and a greetings.js who export the answer

 module.exports= 'Hello';
    });

and get nothing as result, so i define the exports and modules

define( function(exports,module){
module.exports= 'Hello';
});

and get as result:

function localRequire()

what am i doing wrong? i read the documentation and examples, but somehow i can't make this works.

Upvotes: 1

Views: 4796

Answers (1)

Louis
Louis

Reputation: 151401

I'm assuming the require call you are using is RequireJS's require call, not Node's require. (Otherwise, you'd get a very different result.)

You are using the asynchronous form of the require call. With the asynchronous form, there is no return value for you to use, you have to use the callback to get module values, like this:

require(['./greetings.js'], function(sayHi){
  console.log(sayHi);
}); 

However, because you are running in Node, you can do this:

var sayHi = require('./greetings.js'); 

Note how the first argument is a string, not an array of dependencies. This is the synchronous form of the require call. The returned value is the module you required. When you are in Node, RequireJS allows you to call this synchronous form anywhere. When you are running the browser, it is only available inside a define call.

Upvotes: 2

Related Questions