In this video, you watched Node load three of Dana’s files and saw that a module runs once and every file that imports it shares its exports.
Key Points
- When you run
node main.js, Node starts withmain.js. Before any line of it runs, Node finds every import, follows the imports of those files too, and checks that each imported name is really exported. - A module that two files import is loaded only once. Node runs the imported modules first, then
main.jslast. That’s why"budget.js runs"appears once, at the top of the output. - Watch out: because every import is found and checked first, importing a name that isn’t exported stops the whole program with
SyntaxError: ... does not provide an export named .... No file runs, not evenbudget.js. - An import gives you a name for the module’s exported object, not a copy.
main.jsandreport.jseach have a name,budget, and both reach the same object. Whenmain.jsraised the fun limit,report.jssaw the raised limit too. The change lasted only for that run, andbudget.jsitself still saysfun: 150. - It works like two variables in one file that reach one object. That’s as far as the comparison goes, and it’s all you need about imports for now. A what-if budget that’s really separate needs its own copy, which you’ll build later in this course.
- Sharing is also why
budget.jsis worth having, since every file that imports it sees the same limits.
The Final Code
This toy version of the tracker has three short files. budget.js logs a line when it runs and exports Dana’s budget: