0% found this document useful (0 votes)
3 views

Modules

Uploaded by

gagangk8822
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Modules

Uploaded by

gagangk8822
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

MODULES :

• It is ES6 feature.
• Modules are used to break our code into separate files. This helps to
maintain a code base.
• Modules are exported from external file.
• Exported modules are imported with import statements.

Linked using script tag


index.html index.mjs app.js
When you themodules
default ex tdefault expor
Import Logics written here
import port,
From we can
app.js t, weexport
And can use
it
the default ex use any name any name of
port, we can of the the
use any name corresponding corresponding
index.html :
of the object.
object.
corresponding
object.

Note : Browser will not understand modules. So in modules it is mandatory to


mention type = “module” inside the script tag of index.html as shown above

Exporting and importing a module :


Exporting a module :
• JS allows us to export a variables, functions, objects by using the export
keyword.
• There are 2 types of exports
a) Named Exports :
✓ In named exports we can export multiple module.
✓ We are exporting modules (variable, functions, objects) with
their name.
✓ Named exports are imported using { } ({} indicates
destructuring)
✓ Note : In named exports while importing the modules we have
to import it by their names and { } mandatory.
b) Default Exports:
✓ Only one default export in a file.
✓ While importing default exported module we can give any
name.

Importing a module :
• To import a module, we need to use the import keyword.
• To import the modules we need to specify the path .
• When you import the named export, you must have to use the
same name as the corresponding object inside { }.
• When you import the default export, we can give any name.

Named importing and exporting


Ex : In-line individually exporting

app.js
example for variables

index.mjs
Example for function

app.js

index.mjs

Ex : Exporting all at once


app.js

example for variables

index.mjs
Example for function.

app.js

index.js

Default importing and exporting


Examples for variables

app.js

index.js

Example for function


app.js

index.mjs

Note : In index.js file while importing modules from any file it is


mandatory to mention .js extension that is “./app.js”

You might also like