Are modules fully "parsed" before they are used in other files?

49 Views Asked by At

I came across an example in React and I am trying to figure out how and why it works.

function MyComponent() {
 return <h2>{name}</h2>
}

const name = "John";

export default MyComponent;

And in App.js, we're using this component, nothing fancy.

But I expected embedding name within MyComponent's JSX not to work due to how hoisting behaves with let and const, since they're placed in the TDZ until its declaration is reached.

I also tried a simple example in JavaScript.

function myFunc() {
  console.log(name);
}

const name = "John";

export default myFunc;

And in my main.js, I import the function and simply execute it. It also works.

Which makes me think that modules go through the creation and execution phase before its content is used in another file? Or am I involving the execution context wrongly here? What's the explanation?

1

There are 1 best solutions below

0
kca On

What matters is the order of execution, not the position in the code: MDN "temporal dead zone"

The term "temporal" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position)

Your exact use case is described there as well:

For example, the code below works because, even though the function that uses the let variable appears before the variable is declared, the function is called outside the TDZ.

{
  // TDZ starts at beginning of scope
  const func = () => console.log(letVar); // OK

  // Within the TDZ letVar access throws `ReferenceError`

  let letVar = 3; // End of TDZ (for letVar)
  func(); // Called outside TDZ!
}

Modules

JavaScript modules are evaluated when the code that imports them is evaluated.

(I like to think of it as if the imported code would simply be put at the location of the import statement before everything is executed together, which is not correct, but helps me thinking about it.)

MDN "export"

Export declarations are not subject to temporal dead zone rules. You can declare that the module exports X before the name X itself is declared.

export { x };
const x = 1;
// This works, because `export` is only a declaration, but doesn't
// utilize the value of `x`.