알통 지식정보공유

알록달록

ChevronLeft

컴/폰

Javascript ES6 class 와 모듈 (2)

FileX

양재문

2023-02-15 15:00

조회수 : 15

2.모듈

  • -코드의 재사용성을 높인다
  • export , import
  • <script type="module"> 을 추가해야 한다

2-1 기본값 사용(default) - 함수명이 없다

// 동일 경로의 JS 파일

export default ()=>{

console.log('module import!');

}

/!--동일 경로의 html 파일--/

<script type="module">

import 함수명 from './module.js';


함수명();

</script>

2-2 함수명이 있는 함수 사용

// 동일 경로의 JS 파일

export{area,round};


let x = 10;

let y = 20;


let area = ()=>{

return x*y;

}

let round = ()=>{

return (x+y)*2;

}

/!-- 동일경로의 html 파일 --/

<script type="module">


import foo from './module.js';

import {area,round} from './module1.js';

foo();

console.log(area(),round());

</script>

2-3 javascript_es6_module 파일 참조

 

2-4 SPA ( Single Page Application )

html 파일이 하나로 JS로 태그를 작성해 export 한것을 html 로 import 한다.

<!-- 동일경로 HTML -->

<!DOCTYPE html>

<html lang="en">

<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>

<style>

*{margin: 0; padding:0}

#user, #user2, #user3{width: 90%; margin: 0 auto;}

div img{width: 100%; margin-bottom:20px ;}

div dt{text-align: center; font-size: 2em; font-weight: bold; margin-bottom: 20px;}

div dd{line-height: 1.5em; margin-bottom: 20px;}

</style>

</head>

<body>

<div id="user"></div>

<div id="user2"></div>

<div id="user3"></div>


<script type="module">

import str from './module1.js';

import {content,content2} from './module2.js';

str();

content();

content2(2);


</script>


</body>

</html>

// 동일경로 module1 js 파일

export default ()=>{

let str = `

<img src="./images/a1.jpg" alt="">

<dl>

<dt>Avatar : The Way of Water</dt>

<dd>is finally nearing its cinematic debut. The long-anticipated sequel to James Cameron's record-breaking Avatar has managed to hold firm to its final release date.</dd>

<dd>The first teaser arrived online in May, reintroducing us to the beautiful world of Pandora as well as confirming the title was revealed alongside the first teaser trailer</dd>

</dl>`;

document.getElementById('user').innerHTML = str;

}

// 동일경로 module2 js 파일

export{content,content2};


let content = ()=>{

let str = `

<img src="./images/a2.png" alt="">

<dl>

<dt>Avatar : Na'vi</dt>

<dd>The Na'vi (English: The People) are a race of sapient extraterrestrial humanoids who inhabit the lush jungle moon of Pandora.</dd>

</dl>`;


document.getElementById('user2').innerHTML = str;

}


let content2 = (cnt)=>{

let str = `

<img src="./images/a${cnt}.png" alt="">

<dl>

<dt>Avatar : Human</dt>

<dd>Humans are a sapient, bipedal mammalian species native to Earth,

who by the 22nd century has become a technologically advanced species capable of interstellar travel and colonization.</dd>

</dl>`;


document.getElementById('user3').innerHTML = str;

}

 

2,000

7

댓글

  • 브폴로 님이 감사의 마음으로 양재문님께 0알을 증정했어요!

  • 웅이는배고파 님이 감사의 마음으로 양재문님께 0알을 증정했어요!