JavaScript Modules
As our JavaScript code grows in size, there comes a times when one file is not enough - here we're having a look at how to structure code across multiple files using modules.
Enable modules
Given an index.html
file that includes a app.js
file using a script
tag, to enable module, we'll have to include type="module"
:
Default Import/Export
Now, can include functions defines in other files:
... where f1 is exported from within the dependency:
Named Import/Export
An alternative that is usually used when multiple 'transfers' are required is using named exports/imports:
On import, the names must match the exact names from export (order not relevant):
Renamed Export
Function can be renamed as part of the export:
Now, it's imported as f3
:
Renamed Import
Function can also be renamed as part of the import:
Now, it's imported as f3
:
Inline exports
The exports can also happen inline for each function that needs it:
Combined imports: Default & Named
Both of the previous methods can be combined for some interesting results:
Now, the import might look a bit strange:
Passthrough Exports
Say we have 2 dependencies and we don't want to have to import both.
Given a second dependency:
We can simply "pass it through" in the first dependency:
Now app.js
will only have to import from one dependency:
Import all
A great technique that sames keystrokes on import is the ability to import all functions together.
Given:
All exports can be imported together, but the usage is slightly different:
Finally
Classes can also be exported and imported.
Unfortunately, modules are not available in IE (see MDN docs) but are in Edge.
To achieve backward compatibility and avoid multiple HTTP requests in a production environment, we should probably use a module bundler such as Webpack or Babel.