"ReferenceError: window is not defined" when compiling with r.js

1.1k views Asked by At

I've been using RequireJS and it works perfectly. I use a lot of "window.document" to manipulate different DOM elements, but when I try to optimize it with r.js i get a ReferenceError: window is not defined which only happens with r.js.

Here is a minimal example of code that reproduces the issue:

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
}
});

This version works correctly without r.js but when I try to compile it by running r.js main.js. I get this:

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


ReferenceError: window is not defined
         at new new commManager
2

There are 2 answers

0
Louis On

You cannot just do r.js main.js.

For one thing, you have to specify -o so that r.js performs the optimization. (r.js can be used for other things.)

You also have to pass configuration to r.js, either in a file, or on the command line. One possibility for you would be:

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

I've tried this with the code you show in your question and I get no errors.

I strongly suggest going over this documentation for r.js.

0
orellabac On

if your code is optional you can use

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