" ReferenceError:窗口未定义"用r.js编译时

时间:2016-11-21 12:21:19

标签: javascript requirejs r.js

我一直在使用RequireJS,它运行得很好。我使用了很多" window.document"操纵不同的DOM元素,但是当我尝试使用r.js进行优化时,我得到的ReferenceError: window is not defined仅在r.js时出现。

以下是重现问题的代码的最小示例:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body >
<div id="commentbox">

</div>
<script data-main="code/main" src="code/require.js"></script>
</body>
</html>

main.js

 require(["roomManager"], function (roomManager){
 return {

 }
 });

roomManager.js

define(["commentManager"], function(commentManager){
    var commentHand = new commentManager.commentHand();
    commentHand.init();


    return{

    }
});

commentManager.js

define([], function(){
    function commManager(getDisplayIdVariable){
        var messagebox = window.document.getElementById("commentbox");

        this.init = function(){
            messagebox.innerHTML = "hi!";
        }
    }
return{
        commentHand : commManager
}
});

此版本在没有r.js的情况下正常工作,但是当我尝试通过运行r.js main.js进行编译时。我明白了:

var messagebox = window.document.getElementById("commentbox);


ReferenceError: window is not defined
         at new new commManager

2 个答案:

答案 0 :(得分:1)

你不能只做r.js main.js

首先,您必须指定-o,以便r.js执行优化。 (r.js可以用于其他事情。)

您还必须在文件或命令行中将配置传递给r.js。你有一种可能性:

r.js -o name=main out=built.js

我已经尝试使用您在问题中显示的代码,但没有错误。

我强烈建议r.js更新this documentation

答案 1 :(得分:0)

如果您的代码是可选的,则可以使用

 if (typeof window !== 'undefined') { 
       // Inside browser
} 
{
  // outside browser
}