0

For code like this:

const top = document.createElement("div");
top.innerText = "This is the top";
top.style = red;

export { top };

Webpack creates the following:

...

"use strict";
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, "top", function() { return top; });
...

const top = document.createElement("div");
top.innerText = "This is the top";
top.style = red;

How can this be working since inside the getter function() { return top; }, top is not yet defined when the script is executed?

Is there a particular reason why Webpack creates the export at the top and not at the bottom?

Thanks.

stratis
  • 7,750
  • 13
  • 53
  • 94

1 Answers1

3

The entire js file is evaluated as a whole. The section of code that webpack generates is creating a callback function that will be called at a later time. Specifically when the user code requires or imports the module in question.

Later in the script the contents of your module is evaluated and the variable top is defined, and this is guaranteed to happen before webpack executes function() { return top; }

It is only convention to declare, or define variables before they are used in javascript, not a requirement. Function scopes can safely be created with references to variables in a parent scope, which have not been defined yet, as long as they will be defined when the function is executed.

NeoVance
  • 404
  • 2
  • 9
  • 1
    Your last sentence is true, when it’s used in a different function. If you just try to use an undefined variable, you’ll get an error (assuming you were treating it like a dom node and not undefined). But since this variable is in a separate function call, you can safely define the function before the variable as long as you don’t call that method before you define the variable. Since this whole thing is run at once and you can’t inject code into the middle of the file, you’re fine. I think you eluded to this, but I wanted to make it clear, since the question is being asked. – Nate Aug 23 '18 at 05:26
  • Thank you for the clarification @Nate! I think you are right. I May not have been as concise as I should have been. – NeoVance Aug 23 '18 at 05:38