Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ECMAScript Cookbook

You're reading from   ECMAScript Cookbook Over 70 recipes to help you learn the new ECMAScript (ES6/ES8) features and solve common JavaScript problems

Arrow left icon
Product type Paperback
Published in Mar 2018
Publisher Packt
ISBN-13 9781788628174
Length 348 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ross Harrison Ross Harrison
Author Profile Icon Ross Harrison
Ross Harrison
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Building with Modules FREE CHAPTER 2. Staying Compatible with Legacy Browsers 3. Working with Promises 4. Working with async/await and Functions 5. Web Workers, Shared Memory, and Atomics 6. Plain Objects 7. Creating Classes 8. Inheritance and Composition 9. Larger Structures with Design Patterns 10. Working with Arrays 11. Working with Maps and Symbols 12. Working with Sets 13. Other Books You May Enjoy

Nesting modules under a single namespace

As the number of modules grows, patterns start to emerge. For practical and architectural reasons, it makes sense to group multiple modules together and use them as a single package.

This recipe demonstrates how to collect multiple modules together and use them as a single package.

Getting ready

It will be helpful to have the source code available from previous recipes to bootstrap this recipe. Otherwise, you'll need to reference Exporting/importing multiple modules for external use for how to create the index.html file.

How to do it...

  1. Create a new folder with an index.html file, as seen in Exporting/importing multiple modules for external use.
  2. Inside of that directory, create a folder named rockets.
  3. Inside of rockets, create three files: falcon-heavy.js, saturn-v.js, and launch-sequence.js:
// falcon-heavy.js 
import { launchSequence } from './launch-sequence.js'; 
 
export const name = "Falcon Heavy"; 
export const COUNT_DOWN_DURATION = 5; 
 
export function launch () { 
  launchSequence(COUNT_DOWN_DURATION, name); 
} (COUNT_DOWN_DURATION); 
} 
 
// saturn-v.js 
import { launchSequence } from './launch-sequence.js'; 
 
export const name = "Saturn V"; 
export const COUNT_DOWN_DURATION = 10; 
 
export function launch () { 
  launchSequence(COUNT_DOWN_DURATION, name); 
} 
 
// launch-sequence.js 
export function launchSequence (countDownDuration, name) { 
  let currCount = countDownDuration; 
  console.log(`Launching in ${COUNT_DOWN_DURATION}`, name); 
 
  const countDownInterval = setInterval(function () { 
    currCount--; 
 
    if (0 < currCount) { 
      console.log(currCount); 
    } else { 
      console.log('%s LIFTOFF!!! ', name); 
      clearInterval(countDownInterval); 
    } 
  }, 1000); 
} 
  1. Now create index.js, which exports the members of those files:
import * as falconHeavy from './falcon-heavy.js'; 
import * as saturnV from './saturn-v.js'; 
export { falconHeavy, saturnV }; 
  1. Create a main.js file (in the folder that contains rockets), which imports falconHeavey and saturnV from the index.js file and launches them:
import { falconHeavy, saturnV } from './rockets/index.js' 
 
export function main () { 
  saturnV.launch(); 
  falconHeavy.launch(); 
} 
  1. Open in the browser, and see the following output:

How it works...

The * syntax seen on the first two lines of index.js imports all the exported members under the same object. This means that the name, COUNT_DOWN_DURATION, and launch members of falcon-heavey.js are all attached to the falconHeavy variable. Likewise, for the saturn-v.js modules and the saturnV variable. So, when falconHeavy and saturnV are exported on line 4, those exported names now contain all the exported members of their respective modules.

This provides a single point where another module (main.js in this case) can import those members. The pattern has three advantages. It is simple; there is only one file to import members from, rather than many. It is consistent, because all packages can use an index module to expose members of multiple modules. It is more flexible; members of some modules can be used throughout a package and not be exported by the index module.

There's more...

It is possible to export named items directly. Consider the following file, atlas.js:

import { launchSequence } from './launch-sequence.js'; 
 
const name = 'Atlas'; 
const COUNT_DOWN_DURATION = 20; 
 
export const atlas = { 
  name: name, 
  COUNT_DOWN_DURATION: COUNT_DOWN_DURATION, 
  launch: function () { 
    launchSequence(COUNT_DOWN_DURATION, name); 
  } 
}; 

The atlas member can be exported directly by index.js:

import * as falconHeavy from './falcon-heavy.js'; 
import * as saturnV from './saturn-v.js'; 
 
export { falconHeavy, saturnV }; 
export { atlas } from './atlas.js';

Then the main.js file can import the atlas member and launch it:

import { atlas, falconHeavy, saturnV } from './rockets/index.js' 
 
export function main () { 
  saturnV.launch(); 
  falconHeavy.launch(); 
  atlas.launch(); 
} 

This is one benefit of always using named exports; it's easier to collect and export specific members from packages with multiple modules.

Whether named or not, nesting is a great technique for grouping modules. It provides a mechanism for organizing code as the number of modules continues to grow.

You have been reading a chapter from
ECMAScript Cookbook
Published in: Mar 2018
Publisher: Packt
ISBN-13: 9781788628174
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image