어제 살짝 리팩토링 한 깃헙 프로필 넘겨주는 코드를 보다가..
또 비효율적이라는 생각이 들었다. 메인페이지와 서브페이지 둘다
똑같은 로직의 코드를 각각 넣다보니.. 그런것 같았다.
그래서 import, export를 사용해서 모듈화 하는 작업을 해보았다.
// 팀원 깃헙 프로필로 넘겨주는 함수
function openGitHubProfile(url) {
window.open(url);
}
// 배열안에 array로 각각 깃헙 주소 할당
const teamMembers = [
{ id: 'JH', url: 'https://github.com/pesbg123' },
{ id: 'SH', url: 'https://github.com/jrmun' },
{ id: 'JK', url: 'https://github.com/jinkyung127' },
{ id: 'HW', url: 'https://github.com/hyunwoo87' },
{ id: 'HK', url: 'https://github.com/kwakhyunkyu' },
];
// footer에 있는 팀원별 버튼 클릭 이벤트 지정
teamMembers.forEach((member) => {
const clickMember = document.getElementById(member.id);
clickMember.addEventListener('click', () => openGitHubProfile(member.url));
});
기존코드를 쪼개서 js 파일을 2개 만들어서, 하나의 파일에는 export로 밖으로 해당 변수들을 보내주었다
// 팀원 깃헙 프로필로 넘겨주는 함수
export const openGitHubProfile = (url) => {
window.open(url);
};
// 배열안에 array로 각각 깃헙 주소 할당
export const teamMembers = [
{ id: 'JH', url: 'https://github.com/pesbg123' },
{ id: 'SH', url: 'https://github.com/jrmun' },
{ id: 'JK', url: 'https://github.com/jinkyung127' },
{ id: 'HW', url: 'https://github.com/hyunwoo87' },
{ id: 'HK', url: 'https://github.com/kwakhyunkyu' },
];
그럼 이제 나머지 파일에서 import로 받아와서 그것들을 사용해서 기능이 작동하게 구현했다.
import { openGitHubProfile, teamMembers } from '/modules/gitHub_export.js';
// footer에 있는 팀원별 버튼 클릭 이벤트 지정
teamMembers.forEach((member) => {
const clickMember = document.getElementById(member.id);
clickMember.addEventListener('click', () => openGitHubProfile(member.url));
});
그뒤에 메인과 서브의 html body안에 맨밑에 script테그로 연결해주었다.
<script type="module" src="/modules/import.js"></script>
처음에는 type을 text/javascript로 적어서 오류가 났었다. 찾아보니 module로 적어야 한다고 했다.
그래서 수정해주니 잘 동작했다.
<!-- type을 text/javascript로 적었던 코드 -->
<script type="text/javascript" src="/modules/import.js"></script>