0

I am learning about how to create/import/export modules in Node.js, i have gone through these and was trying to learn by creating a sample application. I issued the command from the root folder (Poc1) "npm install requirejs", and included the file require.js in the Start.html.

When i open Start.html in browser i get -

"Uncaught ReferenceError: require is not defined", "Uncaught ReferenceError: module is not defined".

I am not sure what mistake i am making or what other files i need to include to get it working ?

For sample application below is folder structure

Poc1 folder has these files and folders (greetings.js, main.js, Start.html, node_modules)
Poc1\node_modules has (requirejs\require.js)

grreetings.js is defined as below

    module.exports.sayHelloInEnglish = function(){
        return "Hello";
    }

    module.exports.sayHelloInSpanish = function(){
        return "Hola";
    }

main.js is defined as below

    var greetings = require("./greetings.js");
    function someFunc(){
        var g1 = greetings.sayHelloInEnglish();
        var g2 = greetings.sayHelloInSpanish();

        alert(g1);
        alert(g2);
    }

Start.html is defined as below

<html>
<head>
  <script type="text/javascript" src="main.js"></script>
  <script type="text/javascript" src="greetings.js"></script>
  <script type="text/javascript" src="node_modules\requirejs\require.js"></script>
</head>
<body>
  <span>Below is button</span>
  <input type="button" onclick="someFunc()" value="clickMe"/>
</body>
</html>
Sunil Thakur
  • 97
  • 2
  • 11

1 Answers1

0

Ok, I think those exports aren't correct:

exports.sayHelloInEnglish = function(){
    return "Hello";
}

exports.sayHelloInSpanish = function(){
    return "Hola";
}
sailens
  • 1,594
  • 1
  • 17
  • 34
  • Thank you for the answer. I changed the path as suggested and now getting below errors: Uncaught ReferenceError: exports is not defined. Uncaught Error: Module name "greetings.js" has not been loaded yet for context: _. Use require([]) – Sunil Thakur Sep 28 '15 at 08:41
  • @SunilThakur In your HTML file, try put the `` before the `` and see if it solves it. – sailens Sep 28 '15 at 11:54
  • Tried that still the same issue. I tried even creating a node.js package for my module (greetings.js) by using "npm init" command and then specified the new module as a dependency in root.package.json file, however when i run "rootFolder> npm install", npm is unable to find the dependent package (the one which i have created) as it is expecting it there in npm registry, whereas i have not published it yet. I am looking into it. – Sunil Thakur Sep 28 '15 at 12:16