These tutorials talk about import and export of modules in JavaScript ES6.
Why modules in JavaScript?
Module provides code as classes or functions in separate file, that can be used in other modules.
Import and export allows to define the JavaScript and reuse in other modules.
It provides following advantages
- Code reusable
- Code separation
- Modularity namespaces conflict resolution
ES6 introduced following keywords
import
export default
export
import : allows using module features into another modules export: expose the module as ready to use
Javascript export and import default example
export default import a single expression or function for a file or module
Let’s declare a function in module.js
.
Make the function as export default
, it does means that function can be used with import default
syntax.
function getMessage() {
return 'Welcome';
}
export default getMessage
In main.js file, import default unction from module.ts
file
// main.js
import getMessage from './module'
getMessage() // Welcome
Javascript export and import multiple functions example
Let’s declare a calculator file, that contains add, substract functions.
Export both functions
// calculator.js
function add() {
return 'add'
}
function substract() {
return 'substract'
}
export { add, substract }
import both function using import with brackets, contains functions separated by commas.
// main.js
import { add, substract } from './calculator'
add() // add
substract() // substract
default exports don’t have brackets while importing, where as named imports has brackets while import into others code.
Differnce between named and default exports
Default Export | Named Export |
---|---|
It contains only one exports per module or file | Contains multiple exports |
No curly braces during import | curly braces that contains comma separated during import |
duration | time in milliseconds shown before disappear from the page |
panelClass | used to Customize the snackbar css styles |
horizontalPosition | Horizontal position - ‘start’, ‘center’,’end’,’left’, ‘right’ |
verticalPosition | Vertical position - ’top’,‘bottom’ |