Search code examples
javascriptwebpackecmascript-6es6-moduleswebpack-bundle

Order of exports in webpack bundle


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.


Solution

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