반응형
As the size of the project grows bigger, it becomes harder to navigate through the files. To solve this problem, many lagnuages separate the files into small chunk of files such as library of package. JavaScript uses module to solve this.
A module is a group of functions stored separatly in a file to better manage codes. Let's see how we can create module
Implementation
Add the type="module" attribute to the script that is inporting the modules in the main
<!-- index.html -->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://kit.fontawesome.com/833be080c6.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="./main.css">
<script defer type="module" src="./index.js"></script> <!-- main JS -->
</head>
Next, export the functions in the module file
//module.js
function hiWorld() {
console.log('hi')
}
export function byeWorld() { // Export syntax1: exporting individually
console.log('bye')
}
export function withAlias() {
console.log('with alias')
}
// 변수
const one = 1
let two = 2
var three = 3
export {hiWorld, one, two, three} // Export syntax2: exporting all
Note that exported functions must be on the global scope.
export function byeWorld() {
console.log('bye')
var notExported = 'not exported'
}
export {notExported}
index.js
import { hiWorld, byeWorld, withAlias as alias, one, two, three } from './module.js'
hiWorld()
byeWorld()
alias()
console.log(one, two, three)
We have seen how to use module in JavaScript
References
728x90
반응형
'Frontend > JavaScript' 카테고리의 다른 글
Client Side Storage - Indexed DB (0) | 2023.03.31 |
---|---|
Client Side Storage - Web Storage (0) | 2023.03.31 |
Webpack (1) | 2023.03.29 |
Data Request (1) | 2023.03.24 |
Day / Night Mode with JavaScript (1) | 2023.03.24 |