【问题标题】:Uncaught ReferenceError: module/require is not defined未捕获的 ReferenceError:未定义模块/要求
【发布时间】:2015-09-28 06:23:47
【问题描述】:

我正在学习如何在Node.js 中使用create/import/export 模块, 我已经通过these 并试图通过创建示例应用程序来学习。 我从根文件夹(Poc1)"npm install requirejs" 发出了command,并将文件require.js 包含在Start.html 中。

当我在浏览器中打开 Start.html 时,我得到 -

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

我不确定我犯了什么错误或我需要包含哪些其他文件才能使其正常工作?

下面的示例应用程序是文件夹结构

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

greetings.js 定义如下

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

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

main.js 定义如下

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

        alert(g1);
        alert(g2);
    }

Start.html 定义如下

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

【问题讨论】:

    标签: node.js


    【解决方案1】:

    好的,我认为这些导出不正确:

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

    【讨论】:

    • 感谢您的回答。我按照建议更改了路径,现在出现以下错误:未捕获的 ReferenceError:未定义导出。未捕获的错误:尚未为上下文加载模块名称“greetings.js”:_。使用 require([])
    • @SunilThakur 在您的 HTML 文件中,尝试将 &lt;script type="text/javascript" src="greetings.js"&gt;&lt;/script&gt; 放在 &lt;script type="text/javascript" src="main.js"&gt;&lt;/script&gt; 之前,看看是否可以解决。
    • 试过还是同样的问题。我什至尝试使用“npm init”命令为我的模块(greetings.js)创建一个 node.js 包,然后将新模块指定为 root.package.json 文件中的依赖项,但是当我运行“rootFolder> npm install”时",npm 无法在 npm 注册表中找到依赖包(我创建的那个),因为它在 npm 注册表中存在,而我还没有发布它。我正在调查。
    猜你喜欢
    • 2020-05-16
    • 2012-12-16
    • 2017-02-28
    • 2017-06-01
    • 2018-01-30
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多