Modules allow more flexibility in organizing code. This allows for a shorter, more contextual name. For example, in the previous recipe, we named a function launch
instead of something more verbose such as launchRocket
. This helps keep our code more readable, but it also means that different modules can export members that use the same name.
In this recipe, we'll rename imports in order to avoid these namespace collisions.
We'll be reusing the code from the previous recipe (Exporting/importing multiple modules for external use). The changes from the previous files will be highlighted.
- Copy the folder created for the previous recipe into a new directory.
- Navigate to that directory with your command-line application and start the Python server.
- Rename
rocket.js
tosaturn-v.js
, add the name of the rocket to the log statements, and update themain.js
import statement:
// main.js import name, { launch, COUNT_DOWN_DURATION } from './saturn-v.js'; export function main () { console.log('This is a "%s" rocket', name); console.log('It will launch in "%d" seconds.', COUNT_DOWN_DURATION); launch(); } // saturn-v.js export function launch () { console.log(`Launching %s in ${COUNT_DOWN_DURATION}`, name); launchSequence(); } function launchSequence () { // . . . console.log(%shas LIFTOFF!!!', name); // . . . }
- Copy
saturn-v.js
to a new file namedfalcon-heavy.js
and change the default export value and theCOUNT_DOWN_DURATION
:
export default name = "Falcon Heavy";export const COUNT_DOWN_DURATION = 5;
import rocketName, { launch, COUNT_DOWN_DURATION } from './saturn-v.js'; import falconName, { launch as falconLaunch, COUNT_DOWN_DURATION as falconCount } from './falcon-heavy.js'; export function main () { console.log('This is a "%s" rocket', rocketName); console.log('It will launch in "%d" seconds.', COUNT_DOWN_DURATION); launch(); console.log('This is a "%s" rocket', falconName); console.log('It will launch in "%d" seconds.', falconCount); falconLaunch(); }
- Open
index.html
in your browser and you should see the following output:
When we duplicated the saturn-v.js
file to and imported the members from falcon-heavy.js
, we had a potential namespace conflict. Both files export members named COUNT_DOWN_DURATION
and launch. But using the as
keyword, we renamed those members in order to avoid that conflict. Now the importing main.js
file can use both sets of members without issue.
Renaming members can also be helpful to adding context. For example, it might be useful to rename the launch as launchRocket
even if there is no conflict. This give the importing module additional context, and makes the code a bit clearer.