我一直在使用 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
最佳答案
你不能只做 r.js main.js
。
一方面,您必须指定 -o
以便 r.js
执行优化。 (r.js
可以用于其他事情。)
您还必须通过文件或命令行将配置传递给 r.js
。您的一种可能性是:
r.js -o name=main out=built.js
我已经使用您在问题中显示的代码进行了尝试,没有发现任何错误。
我强烈建议查看 this documentation对于 r.js
。
关于javascript - 使用 r.js 编译时为 "ReferenceError: window is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720073/