Import and Export
What Import and Export Do
ES6 introduced a standard syntax for sharing JS functionalities between files in a controlled, manageable way (such as avoiding variables leaking into global scope).
importis how you decide what other code is included in a file
exportis how you decide what code can be shared with others
Exporting is usually defined at the end of a file, using the final written functions or classes. A simple example exporting variable values could look like this:
You can then reference this file (with vanilla JS it usually takes a relative path) and import some or all of what was exported.
You can quickly import all exported items into an object.
Exports let you set a default item to be exported, which can be more easily referenced and used when imported.
The default export is the object with all these values. You can import that, or import specific ones from the other export, with this setup.
Import with Destructuring
A common way to handle export/import reliably is the following:
- Export an object as the default
- Use JS Destructuring to import specific pieces as needed, or all of them into one variable