简体   繁体   中英

How are es6 imports and exports handled? (Javascript)

I have a bug in my code that has something to do with imports and exports. My understanding was that all imports are handled before any code is run, however now I am not so sure. I have the following MRE below, in three files.

index.html

<!-- index.html (Program entry point) -->
<html>
   <head>
      <script src="A.js" type="module"></script>
   </head>
    <body></body>
</html>

A.js

// A.js

import './B.js';

export default 'Hello World';

B.js

// B.js

import message from './A.js';

console.log(message);

When run, produces this error: Uncaught ReferenceError: Cannot access 'message' before initialization at B.js:5

To make things stranger, if I make index.html instead point to B.js , then the program runs fine (Without changing any other files).

My prior understanding was that all imports/exports would be evaluated first, and only then the rest of the code run. However this snippet seems to suggest that the 'import chain' is followed down, and then each file evaluated from the bottom up, bringing each export with it. Meaning that if a file 'lower' on the import tree needs an export from something above it, then it just doesn't work. But to me that would be very strange and counter-intuative behaviour.

So my question is, what is the cause? Is my understanding of the order how imports/exports are evaluated wrong? Or is this a bug in Chrome/Edge? (Unfortunately couldn't test any others) Or am I missing something else???

Why does this behave the way it does?

Thanks for any help

- Keldan

In A.js don't import B.js

// A.js

export default 'Hello World';

Otherwise you will have a circular dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM