Skip to content

Latest commit

 

History

History
79 lines (49 loc) · 2.47 KB

File metadata and controls

79 lines (49 loc) · 2.47 KB

Module #14 - ES Modules and structuring Larger Apps


Modules

Modules are a way to structure and organize Javascript to share functionality and data across multiple files and/or projects.

Characteristics:

  • Modules have their own scope, we don't need to worry about global variables.

    NOTE: variables that you create inside a module it will be available only in that file, nowhere else

  • Modules can hold anything (functionality, data, config, etc).

Supposing that we have the following structure:

Modules structure

we can load each javascript file in the body like:

<body>
  <script src="./utils.js"></script>
  <script src="./handlers.js"></script>
  <script src="./script.js"></script>
</body>

but instead of doing that, we can use modules and use the script.js as our entry point and share data, functionality etc with modules by adding the attribute type and set to module:

<body>
  <script src="./script.js" type="module"></script>
</body>

if we need to use a function that is our utils.js we can imported into our script.js

there are two types to export files

  • named exports: they have the export word in front of the variable declaration/function definition or when they exported there will be curly brackets.
    You can have as many named exports as you want.

    namedExports

  • default exports: you can have only one per module, you can exports default as follow

    namedExports

there are two types to export files

  • named imports: you need to use the word import then in curly brackets the named exports and the path when you want to import, in this case util.js

    namedImports

  • default imports:

    importDefault

you can rename the import as you wanted, for example the returnHi function to sayHi

renameImports

Documentation:

modules
imports
exports



back to Table of Content
previous Ajax and fetching data
next Final round exercises