These rules could become frustrating when one file depended on a variable defined by another file, particularly when the first file was evaluated after the second file.
Thanks to modules, any load-order dependency you might imagine can be resolved by adding an import statement. So if a.js loads before b.js because of their file names, but a.js
needs something defined by b.js
, then a.js
can simply import
that value from b.js
:
// a.js
import { bThing } from './b';
console.log(bThing, 'in a.js');
// b.js
export var bThing = 'a thing defined in b.js';
console.log(bThing, 'in b.js');
Sometimes a module doesn’t actually need to import
anything from another module, but you still want to be sure the other module gets evaluated first. In such situations, you can use an even simpler import syntax:
// c.js
import './a';
console.log('in c.js');
No matter which of these modules is imported first, the order of the console.log
calls will always be :
console.log(bThing, 'in b.js');
console.log(bThing, 'in a.js');
console.log('in c.js');