A module is just a file. One script is one module. As simple as that.
Using the keywords “export” and “import,” we can move code (function, variable) from one module to another, dividing a large script into manageable modules. We use “export” keyword for code in module that needs to be used outside of module. we add code from other modules to a module by using import keyword. there are two main types of import and export in js.
| Feature | Named Exports | Default Export |
|---|---|---|
| Syntax | export { name1, name2 ... }; |
export default something; |
| Import Syntax | import { name1, name2 ... } from './module.js'; |
import anyName from './module.js'; |
| Number | Multiple per module | Only one per module |
| Use Case | Exporting a collection of related functions/values | Exporting the main "thing" from a module |
| Flexibility | Less flexible imports (names must match) | More flexible imports (any name can be used) |
| Best Practice | When you have many values to export | When you have one primary value to export |
this is undefined. Compare it to non-module scripts, where this is a global objectModern build tools, such as webpack and others, bundle modules together and optimize them to speedup loading. They also remove unused imports.
For instance, if you import * as library from a huge code library, and then use only few methods, then unused ones will not be included into the optimized bundle.