Ver3.0 ๐ JavaScript ๋ผ์ฐํ ๊ณผ SPA ๋ค๋น๊ฒ์ด์ ๊ตฌํ ์ ๋ต: ํ๋์ ์ธ ์น ์ฑ์ ์ํ ์๋ฒฝ ๊ฐ์ด๋

๐ JavaScript ๋ผ์ฐํ ๊ณผ SPA ๋ค๋น๊ฒ์ด์ ๊ตฌํ ์ ๋ต: ํ๋์ ์ธ ์น ์ฑ์ ์ํ ์๋ฒฝ ๊ฐ์ด๋
์น๊ตฌ์ฒ๋ผ ์ฝ๊ณ ์ฌ๋ฏธ์๊ฒ ๋ฐฐ์ฐ๋ ํ๋ก ํธ์๋ ๋ค๋น๊ฒ์ด์ ์ ๋ชจ๋ ๊ฒ
๐ฏ ์๋ , ์น๊ตฌ! ์ค๋์ ์ ๋ง ์ค์ํ ์ฃผ์ ๋ฅผ ๊ฐ์ง๊ณ ์์ด. ๋ฐ๋ก JavaScript ๋ผ์ฐํ ๊ณผ SPA ๋ค๋น๊ฒ์ด์ ์ด์ผ. ์์ฆ ์น ๊ฐ๋ฐํ๋ฉด์ ์ด๊ฑฐ ๋ชจ๋ฅด๋ฉด ์ง์ง ๊ณค๋ํ๊ฑฐ๋ ? ๐
๋ทํ๋ฆญ์ค๋ ์ ํ๋ธ ์ธ ๋ ํ์ด์ง๊ฐ ๊น๋นก์ด์ง ์๊ณ ๋ถ๋๋ฝ๊ฒ ์ ํ๋๋ ๊ฑฐ ๋๊ปด๋ดค์ง? ๊ทธ๊ฒ ๋ฐ๋ก SPA(Single Page Application)์ ๋ง๋ฒ์ด์ผ! ์ด ๊ธ์์๋ ๊ทธ ๋ง๋ฒ์ ์ง์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ์๋ ค์ค๊ฒ. ์ด๋ณด์๋ ์ดํดํ ์ ์๊ฒ ์ฐจ๊ทผ์ฐจ๊ทผ ์ค๋ช ํ ํ ๋๊น ๊ฑฑ์ ๋ง! ๐ช
๐ค SPA์ ๋ผ์ฐํ , ๋๋์ฒด ๋ญ๊ธธ๋?
๋จผ์ ๊ธฐ๋ณธ ๊ฐ๋ ๋ถํฐ ํ์คํ ์ก๊ณ ๊ฐ์! ์ ํต์ ์ธ ์น์ฌ์ดํธ๋ ๋งํฌ๋ฅผ ํด๋ฆญํ ๋๋ง๋ค ์๋ฒ์์ ์์ ํ ์๋ก์ด HTML ํ์ด์ง๋ฅผ ๋ฐ์์. ๊ทธ๋์ ํ๋ฉด์ด ๊น๋นก์ด๊ณ ๋ก๋ฉ ์๊ฐ์ด ๊ฑธ๋ฆฌ์ง. ๐ด
ํ์ง๋ง SPA(Single Page Application)๋ ๋ค๋ฅด๊ฒ ์๋ํด. ์ฒ์ ํ ๋ฒ๋ง ํ์ด์ง๋ฅผ ๋ก๋ํ๊ณ , ๊ทธ ๋ค์๋ถํฐ๋ JavaScript๊ฐ ํ์ํ ๋ถ๋ถ๋ง ๋์ ์ผ๋ก ๋ฐ๊ฟ์ฃผ๋ ๊ฑฐ์ผ. ๋ง์น ์ฑ ์ ํ์ด์ง๋ฅผ ๋๊ธฐ๋ ๊ฒ์ฒ๋ผ ๋ถ๋๋ฝ๊ฒ!
๐ ํต์ฌ ์ฉ์ด ์ ๋ฆฌ
โข SPA (Single Page Application): ํ๋์ HTML ํ์ด์ง์์ JavaScript๋ก ์ฝํ ์ธ ๋ฅผ ๋์ ์ผ๋ก ๋ณ๊ฒฝํ๋ ์น ์ ํ๋ฆฌ์ผ์ด์
โข ๋ผ์ฐํ (Routing): URL ๊ฒฝ๋ก์ ๋ฐ๋ผ ์ ์ ํ ์ฝํ ์ธ ๋ฅผ ๋ณด์ฌ์ฃผ๋ ๋ฉ์ปค๋์ฆ
โข ๋ค๋น๊ฒ์ด์ (Navigation): ์ฌ์ฉ์๊ฐ ์ฑ ๋ด์์ ์ด๋ํ๋ ๊ณผ์
โข History API: ๋ธ๋ผ์ฐ์ ์ ๋ฐฉ๋ฌธ ๊ธฐ๋ก์ ์กฐ์ํ ์ ์๋ JavaScript API
๐ฏ ์ ๋ผ์ฐํ ์ด ์ค์ํ ๊น?
๋ผ์ฐํ ์ SPA์ ์ฌ์ฅ์ด๋ผ๊ณ ํ ์ ์์ด. ๋ผ์ฐํ ์ด ์์ผ๋ฉด SPA๋ ๊ทธ๋ฅ ๋จ์ผ ํ์ด์ง์ผ ๋ฟ์ด์ผ. ํ์ง๋ง ๋ผ์ฐํ ์ ์ถ๊ฐํ๋ฉด:
๐ URL ๊ด๋ฆฌ
๊ฐ ํ๋ฉด๋ง๋ค ๊ณ ์ ํ URL์ ๊ฐ์ง ์ ์์ด. ๋ถ๋งํฌ๋ ๊ฐ๋ฅํ๊ณ ๊ณต์ ๋ ์ฌ์์ง์ง!
โฎ๏ธ ๋ธ๋ผ์ฐ์ ํ์คํ ๋ฆฌ
๋ค๋ก ๊ฐ๊ธฐ, ์์ผ๋ก ๊ฐ๊ธฐ ๋ฒํผ์ด ์ ์์ ์ผ๋ก ์๋ํด. ์ฌ์ฉ์๊ฐ ๊ธฐ๋ํ๋ ๋๋ก!
๐จ ์ฌ์ฉ์ ๊ฒฝํ
ํ์ด์ง ์๋ก๊ณ ์นจ ์์ด ๋ถ๋๋ฌ์ด ์ ํ. ์ด๊ฒ ๋ฐ๋ก ํ๋์ ์ธ ์น์ ๋๋์ด์ผ!
์ค์ ์ฌ๋ก: ๊ตฌ๊ธ ์ง๋๋ฅผ ์๊ฐํด๋ด. ์ง๋๋ฅผ ์ด๋ํ๊ฑฐ๋ ๊ฒ์ํ ๋๋ง๋ค URL์ด ๋ฐ๋์ง๋ง ํ์ด์ง๋ ์๋ก๊ณ ์นจ๋์ง ์์. ์ด๊ฒ ๋ฐ๋ก ๋ผ์ฐํ ์ ํ์ด์ผ! ๐บ๏ธ
๐ ๏ธ ๋ผ์ฐํ ์ ๋ ๊ฐ์ง ๋ฐฉ์
JavaScript์์ ๋ผ์ฐํ ์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ํฌ๊ฒ ๋ ๊ฐ์ง์ผ. ๊ฐ๊ฐ ์ฅ๋จ์ ์ด ์์ผ๋๊น ์ํฉ์ ๋ง๊ฒ ์ ํํ๋ฉด ๋ผ!
1๏ธโฃ Hash ๊ธฐ๋ฐ ๋ผ์ฐํ (#)
URL์ ํด์(#)๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ์์ด์ผ. ์๋ฅผ ๋ค๋ฉด example.com/#/about ์ด๋ฐ ์์ด์ง.
โ ์ฅ์
โข ์๋ฒ ์ค์ ์ด ํ์ ์์ด (ํด์ ๋ค์ ๋ด์ฉ์ ์๋ฒ๋ก ์ ์ก๋์ง ์์)
โข ๊ตฌํ ๋ธ๋ผ์ฐ์ ์์๋ ์ ์๋ํด
โข ๊ตฌํ์ด ๊ฐ๋จํด
โข GitHub Pages ๊ฐ์ ์ ์ ํธ์คํ ์์๋ ๋ฌธ์ ์์ด ์๋
โ ๋จ์
โข URL์ด ์ข ์ง์ ๋ถํด ๋ณด์ฌ (#์ด ๋ค์ด๊ฐ๋๊น)
โข SEO(๊ฒ์ ์์ง ์ต์ ํ)์ ๋ถ๋ฆฌํ ์ ์์ด
โข ์ ๋ฌธ์ ์ด์ง ์์ ๋ณด์ผ ์ ์์ด
์ฝ๋ ์์ ๋ฅผ ๋ณผ๊น?
// Hash ๊ธฐ๋ฐ ๋ผ์ฐํฐ ๊ธฐ๋ณธ ๊ตฌ์กฐ
class HashRouter {
constructor(routes) {
this.routes = routes;
this.currentPath = '';
// hashchange ์ด๋ฒคํธ ๋ฆฌ์ค๋ ๋ฑ๋ก
window.addEventListener('hashchange', () => {
this.handleRoute();
});
// ์ด๊ธฐ ๋ก๋
this.handleRoute();
}
handleRoute() {
// ํ์ฌ ํด์ ๊ฐ ๊ฐ์ ธ์ค๊ธฐ (# ์ ๊ฑฐ)
this.currentPath = window.location.hash.slice(1) || '/';
// ๋งค์นญ๋๋ ๋ผ์ฐํธ ์ฐพ๊ธฐ
const route = this.routes[this.currentPath];
if (route) {
// ๋ผ์ฐํธ๊ฐ ์์ผ๋ฉด ํด๋น ์ปดํฌ๋ํธ ๋ ๋๋ง
this.render(route.component);
} else {
// 404 ์ฒ๋ฆฌ
this.render(this.routes['/404']?.component || 'ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค');
}
}
render(component) {
const app = document.getElementById('app');
if (typeof component === 'function') {
app.innerHTML = component();
} else {
app.innerHTML = component;
}
}
navigate(path) {
window.location.hash = path;
}
}
// ์ฌ์ฉ ์์
const routes = {
'/': {
component: () => '<h1>ํ ํ์ด์ง</h1><p>ํ์ํฉ๋๋ค! ๐ </p>'
},
'/about': {
component: () => '<h1>์๊ฐ ํ์ด์ง</h1><p>์ฐ๋ฆฌ๋ ๋ฉ์ง ํ์
๋๋ค! ๐ฅ</p>'
},
'/contact': {
component: () => '<h1>์ฐ๋ฝ์ฒ</h1><p>์ธ์ ๋ ์ฐ๋ฝ์ฃผ์ธ์! ๐ง</p>'
},
'/404': {
component: () => '<h1>404</h1><p>ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ด์ ๐ข</p>'
}
};
const router = new HashRouter(routes);
// ํ๋ก๊ทธ๋๋ฐ ๋ฐฉ์์ผ๋ก ๋ค๋น๊ฒ์ด์
// router.navigate('/about');
2๏ธโฃ History API ๊ธฐ๋ฐ ๋ผ์ฐํ
HTML5์์ ์ ๊ณตํ๋ History API๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ์์ด์ผ. URL์ด example.com/about ์ฒ๋ผ ๊น๋ํ๊ฒ ๋์!
โ ์ฅ์
โข URL์ด ๊น๋ํ๊ณ ์ ๋ฌธ์ ์ผ๋ก ๋ณด์ฌ
โข SEO์ ์ ๋ฆฌํด (๊ฒ์ ์์ง์ด ํฌ๋กค๋งํ๊ธฐ ์ข์)
โข ์ฌ์ฉ์ ๊ฒฝํ์ด ๋ ์์ฐ์ค๋ฌ์
โข ํ๋์ ์ธ ์น ์ฑ์ ํ์ค
โ ๋จ์
โข ์๋ฒ ์ค์ ์ด ํ์ํด (๋ชจ๋ ๊ฒฝ๋ก๋ฅผ index.html๋ก ๋ฆฌ๋ค์ด๋ ํธ)
โข ๊ตฌํ ๋ธ๋ผ์ฐ์ ์์ ์ง์ ์ ๋ ์ ์์ด
โข ๊ตฌํ์ด ์กฐ๊ธ ๋ ๋ณต์กํด
History API ๋ผ์ฐํฐ ๊ตฌํํด๋ณด์!
// History API ๊ธฐ๋ฐ ๋ผ์ฐํฐ
class HistoryRouter {
constructor(routes) {
this.routes = routes;
this.currentPath = '';
// popstate ์ด๋ฒคํธ (๋ค๋ก/์์ผ๋ก ๊ฐ๊ธฐ)
window.addEventListener('popstate', (e) => {
this.handleRoute(window.location.pathname);
});
// ๋งํฌ ํด๋ฆญ ๊ฐ๋ก์ฑ๊ธฐ
document.addEventListener('click', (e) => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
this.navigate(e.target.getAttribute('href'));
}
});
// ์ด๊ธฐ ๋ก๋
this.handleRoute(window.location.pathname);
}
handleRoute(path) {
this.currentPath = path || '/';
// ๋ผ์ฐํธ ๋งค์นญ (๋์ ๋ผ์ฐํธ ์ง์)
let matchedRoute = null;
let params = {};
for (let routePath in this.routes) {
const match = this.matchRoute(routePath, this.currentPath);
if (match.isMatch) {
matchedRoute = this.routes[routePath];
params = match.params;
break;
}
}
if (matchedRoute) {
this.render(matchedRoute.component, params);
} else {
this.render(this.routes['/404']?.component || '404 Not Found');
}
}
matchRoute(routePath, urlPath) {
// ๋์ ํ๋ผ๋ฏธํฐ ์ง์ (/user/:id ๊ฐ์ ํํ)
const routeParts = routePath.split('/');
const urlParts = urlPath.split('/');
if (routeParts.length !== urlParts.length) {
return { isMatch: false, params: {} };
}
const params = {};
for (let i = 0; i < routeParts.length; i++) {
if (routeParts[i].startsWith(':')) {
// ๋์ ํ๋ผ๋ฏธํฐ
const paramName = routeParts[i].slice(1);
params[paramName] = urlParts[i];
} else if (routeParts[i] !== urlParts[i]) {
return { isMatch: false, params: {} };
}
}
return { isMatch: true, params };
}
render(component, params = {}) {
const app = document.getElementById('app');
if (typeof component === 'function') {
app.innerHTML = component(params);
} else {
app.innerHTML = component;
}
}
navigate(path) {
// History API๋ก URL ๋ณ๊ฒฝ (ํ์ด์ง ์๋ก๊ณ ์นจ ์์ด)
window.history.pushState({}, '', path);
this.handleRoute(path);
}
back() {
window.history.back();
}
forward() {
window.history.forward();
}
}
// ์ฌ์ฉ ์์
const routes = {
'/': {
component: () => `
<h1>ํ ํ์ด์ง ๐ </h1>
<p>ํ์ํฉ๋๋ค!</p>
<a href="/about" data-link>์๊ฐ ํ์ด์ง๋ก</a>
`
},
'/about': {
component: () => `
<h1>์๊ฐ ํ์ด์ง ๐ฅ</h1>
<p>์ฐ๋ฆฌ๋ ๋ฉ์ง ๊ฐ๋ฐ์๋ค์
๋๋ค!</p>
<a href="/" data-link>ํ์ผ๋ก</a>
`
},
'/user/:id': {
component: (params) => `
<h1>์ฌ์ฉ์ ํ๋กํ ๐ค</h1>
<p>์ฌ์ฉ์ ID: ${params.id}</p>
<a href="/" data-link>ํ์ผ๋ก</a>
`
},
'/404': {
component: () => `
<h1>404 ๐ข</h1>
<p>ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค</p>
<a href="/" data-link>ํ์ผ๋ก ๋์๊ฐ๊ธฐ</a>
`
}
};
const router = new HistoryRouter(routes);
โ๏ธ ์๋ฒ ์ค์ ๊ฐ์ด๋
History API๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ์๋ฒ ์ค์ ์ด ํ์ํ๋ค๊ณ ํ์ง? ๊ฐ ์๋ฒ๋ณ๋ก ์ด๋ป๊ฒ ์ค์ ํ๋์ง ์์๋ณด์!
Apache (.htaccess)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
location / {
try_files $uri $uri/ /index.html;
}
Node.js (Express)
const express = require('express');
const path = require('path');
const app = express();
// ์ ์ ํ์ผ ์ ๊ณต
app.use(express.static(path.join(__dirname, 'public')));
// ๋ชจ๋ ๊ฒฝ๋ก๋ฅผ index.html๋ก
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(3000, () => {
console.log('์๋ฒ๊ฐ 3000๋ฒ ํฌํธ์์ ์คํ ์ค! ๐');
});
๐จ ์ค์ ๋ผ์ฐํฐ ๊ตฌํํ๊ธฐ
์ด์ ์ง์ง ์ค๋ฌด์์ ์ธ ์ ์๋ ๋ผ์ฐํฐ๋ฅผ ๋ง๋ค์ด๋ณด์! ๋ค์ํ ๊ธฐ๋ฅ์ ์ถ๊ฐํด๋ณผ๊ฒ.
๊ณ ๊ธ ๊ธฐ๋ฅ์ด ํฌํจ๋ ๋ผ์ฐํฐ
class AdvancedRouter {
constructor(routes, options = {}) {
this.routes = routes;
this.currentPath = '';
this.params = {};
this.query = {};
this.beforeEachHooks = [];
this.afterEachHooks = [];
this.mode = options.mode || 'history'; // 'history' or 'hash'
this.init();
}
init() {
if (this.mode === 'history') {
window.addEventListener('popstate', () => {
this.handleRoute(window.location.pathname);
});
document.addEventListener('click', (e) => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
this.navigate(e.target.getAttribute('href'));
}
});
} else {
window.addEventListener('hashchange', () => {
this.handleRoute(window.location.hash.slice(1));
});
}
const initialPath = this.mode === 'history'
? window.location.pathname
: window.location.hash.slice(1) || '/';
this.handleRoute(initialPath);
}
// ๋ค๋น๊ฒ์ด์
๊ฐ๋ (๋ผ์ฐํธ ์ด๋ ์ ์คํ)
beforeEach(hook) {
this.beforeEachHooks.push(hook);
}
// ๋ค๋น๊ฒ์ด์
ํ ์คํ
afterEach(hook) {
this.afterEachHooks.push(hook);
}
async handleRoute(path) {
const from = this.currentPath;
const to = path || '/';
// ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ํ์ฑ
const [pathname, queryString] = to.split('?');
this.query = this.parseQuery(queryString);
// beforeEach ํ
์คํ
for (let hook of this.beforeEachHooks) {
const result = await hook(to, from);
if (result === false) {
// ๋ค๋น๊ฒ์ด์
์ทจ์
return;
}
if (typeof result === 'string') {
// ๋ฆฌ๋ค์ด๋ ํธ
this.navigate(result);
return;
}
}
// ๋ผ์ฐํธ ๋งค์นญ
let matchedRoute = null;
let params = {};
for (let routePath in this.routes) {
const match = this.matchRoute(routePath, pathname);
if (match.isMatch) {
matchedRoute = this.routes[routePath];
params = match.params;
break;
}
}
if (matchedRoute) {
this.currentPath = to;
this.params = params;
// ๋ฉํ ์ ๋ณด ์ฒ๋ฆฌ (ํ์ด์ง ํ์ดํ ๋ฑ)
if (matchedRoute.meta) {
this.handleMeta(matchedRoute.meta);
}
await this.render(matchedRoute.component, params, this.query);
// afterEach ํ
์คํ
for (let hook of this.afterEachHooks) {
await hook(to, from);
}
} else {
this.render(this.routes['/404']?.component || '404 Not Found');
}
}
matchRoute(routePath, urlPath) {
const routeParts = routePath.split('/').filter(p => p);
const urlParts = urlPath.split('/').filter(p => p);
if (routeParts.length !== urlParts.length) {
return { isMatch: false, params: {} };
}
const params = {};
for (let i = 0; i < routeParts.length; i++) {
if (routeParts[i].startsWith(':')) {
const paramName = routeParts[i].slice(1);
params[paramName] = decodeURIComponent(urlParts[i]);
} else if (routeParts[i] !== urlParts[i]) {
return { isMatch: false, params: {} };
}
}
return { isMatch: true, params };
}
parseQuery(queryString) {
if (!queryString) return {};
const query = {};
const pairs = queryString.split('&');
for (let pair of pairs) {
const [key, value] = pair.split('=');
query[decodeURIComponent(key)] = decodeURIComponent(value || '');
}
return query;
}
handleMeta(meta) {
if (meta.title) {
document.title = meta.title;
}
if (meta.description) {
let metaDesc = document.querySelector('meta[name="description"]');
if (!metaDesc) {
metaDesc = document.createElement('meta');
metaDesc.name = 'description';
document.head.appendChild(metaDesc);
}
metaDesc.content = meta.description;
}
}
async render(component, params = {}, query = {}) {
const app = document.getElementById('app');
if (typeof component === 'function') {
const result = component({ params, query, router: this });
// Promise ์ง์ (๋น๋๊ธฐ ์ปดํฌ๋ํธ)
if (result instanceof Promise) {
app.innerHTML = '<div class="loading">๋ก๋ฉ ์ค... โณ</div>';
app.innerHTML = await result;
} else {
app.innerHTML = result;
}
} else {
app.innerHTML = component;
}
}
navigate(path, replace = false) {
if (this.mode === 'history') {
if (replace) {
window.history.replaceState({}, '', path);
} else {
window.history.pushState({}, '', path);
}
this.handleRoute(path);
} else {
window.location.hash = path;
}
}
back() {
window.history.back();
}
forward() {
window.history.forward();
}
// ํ์ฌ ๋ผ์ฐํธ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
getCurrentRoute() {
return {
path: this.currentPath,
params: this.params,
query: this.query
};
}
}
// ์ค์ ์ฌ์ฉ ์์
const routes = {
'/': {
component: () => `
<div class="page">
<h1>ํ ํ์ด์ง ๐ </h1>
<p>์ฌ๋ฅ๋ท์์ ๋ค์ํ ๊ฐ๋ฐ ์ฌ๋ฅ์ ๊ณต์ ํด๋ณด์ธ์!</p>
<nav>
<a href="/about" data-link>์๊ฐ</a> |
<a href="/user/123" data-link>์ฌ์ฉ์ ํ๋กํ</a> |
<a href="/search?q=javascript&sort=latest" data-link>๊ฒ์</a>
</nav>
</div>
`,
meta: {
title: 'ํ - ๋ด ๋ฉ์ง SPA',
description: 'SPA ๋ผ์ฐํ
์์ ํํ์ด์ง'
}
},
'/about': {
component: () => `
<div class="page">
<h1>์๊ฐ ํ์ด์ง ๐ฅ</h1>
<p>์ฐ๋ฆฌ๋ JavaScript๋ฅผ ์ฌ๋ํ๋ ๊ฐ๋ฐ์๋ค์
๋๋ค!</p>
<a href="/" data-link>โ ํ์ผ๋ก</a>
</div>
`,
meta: {
title: '์๊ฐ - ๋ด ๋ฉ์ง SPA'
}
},
'/user/:id': {
component: ({ params }) => `
<div class="page">
<h1>์ฌ์ฉ์ ํ๋กํ ๐ค</h1>
<p>์ฌ์ฉ์ ID: <strong>${params.id}</strong></p>
<a href="/" data-link>โ ํ์ผ๋ก</a>
</div>
`,
meta: {
title: '์ฌ์ฉ์ ํ๋กํ'
}
},
'/search': {
component: ({ query }) => `
<div class="page">
<h1>๊ฒ์ ๊ฒฐ๊ณผ ๐</h1>
<p>๊ฒ์์ด: <strong>${query.q || '์์'}</strong></p>
<p>์ ๋ ฌ: <strong>${query.sort || '๊ธฐ๋ณธ'}</strong></p>
<a href="/" data-link>โ ํ์ผ๋ก</a>
</div>
`
},
'/protected': {
component: () => `
<div class="page">
<h1>๋ณดํธ๋ ํ์ด์ง ๐</h1>
<p>์ธ์ฆ๋ ์ฌ์ฉ์๋ง ๋ณผ ์ ์์ต๋๋ค!</p>
</div>
`
},
'/404': {
component: () => `
<div class="page">
<h1>404 ๐ข</h1>
<p>ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค</p>
<a href="/" data-link>ํ์ผ๋ก ๋์๊ฐ๊ธฐ</a>
</div>
`
}
};
const router = new AdvancedRouter(routes, { mode: 'history' });
// ๋ค๋น๊ฒ์ด์
๊ฐ๋ ์์ (์ธ์ฆ ์ฒดํฌ)
router.beforeEach((to, from) => {
console.log(`${from} โ ${to} ์ด๋ ์ค...`);
// ๋ณดํธ๋ ํ์ด์ง ์ ๊ทผ ์ ์ธ์ฆ ์ฒดํฌ
if (to === '/protected') {
const isAuthenticated = false; // ์ค์ ๋ก๋ ์ธ์ฆ ์ํ ์ฒดํฌ
if (!isAuthenticated) {
alert('๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค!');
return '/'; // ํ์ผ๋ก ๋ฆฌ๋ค์ด๋ ํธ
}
}
// ๊ณ์ ์งํ
return true;
});
// ํ์ด์ง ์ด๋ ํ ์คํฌ๋กค ๋งจ ์๋ก
router.afterEach(() => {
window.scrollTo(0, 0);
});
๐ ์! ์ด์ ์ง์ง ์ค๋ฌด๊ธ ๋ผ์ฐํฐ๊ฐ ์์ฑ๋์ด! ์ด ๋ผ์ฐํฐ๋:
โข ๋์ ๋ผ์ฐํธ ํ๋ผ๋ฏธํฐ ์ง์ (/user/:id)
โข ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ํ์ฑ (?q=search&sort=latest)
โข ๋ค๋น๊ฒ์ด์ ๊ฐ๋ (beforeEach, afterEach)
โข ๋ฉํ ์ ๋ณด ๊ด๋ฆฌ (ํ์ด์ง ํ์ดํ, ์ค๋ช )
โข ๋น๋๊ธฐ ์ปดํฌ๋ํธ ์ง์
โข History API์ Hash ๋ชจ๋ ๋ชจ๋ ์ง์
์ด ์ ๋๋ฉด ์ค์๊ท๋ชจ ํ๋ก์ ํธ์์ ์ถฉ๋ถํ ์ธ ์ ์์ด! ๐ช
๐ ์ธ๊ธฐ ๋ผ์ฐํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค
๋ฌผ๋ก ์ง์ ๋ง๋ค์ด ์ฐ๋ ๊ฒ๋ ์ข์ง๋ง, ์ค๋ฌด์์๋ ๊ฒ์ฆ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฐ๋ ๊ฒ ๋ ์์ ํ๊ณ ํจ์จ์ ์ด์ผ. ๋ํ์ ์ธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ ์๊ฐํ ๊ฒ!
| ๋ผ์ด๋ธ๋ฌ๋ฆฌ | ํ๋ ์์ํฌ | ํน์ง | ์ธ๊ธฐ๋ |
|---|---|---|---|
| React Router | React | ๊ฐ์ฅ ์ธ๊ธฐ ์๋ React ๋ผ์ฐํ ์๋ฃจ์ | โญโญโญโญโญ |
| Vue Router | Vue.js | Vue ๊ณต์ ๋ผ์ฐํฐ, ์ง๊ด์ ์ธ API | โญโญโญโญโญ |
| Angular Router | Angular | Angular ๋ด์ฅ ๋ผ์ฐํฐ, ๊ฐ๋ ฅํ ๊ธฐ๋ฅ | โญโญโญโญ |
| Page.js | Vanilla JS | ๊ฐ๋ณ๊ณ ๊ฐ๋จํ ํด๋ผ์ด์ธํธ ๋ผ์ฐํฐ | โญโญโญ |
| Navigo | Vanilla JS | ์์กด์ฑ ์๋ ์์ JS ๋ผ์ฐํฐ | โญโญโญ |
React Router ์์
React๋ฅผ ์ด๋ค๋ฉด React Router๊ฐ ์ฌ์ค์ ํ์ค์ด์ผ. ๊ฐ๋จํ ์์ ๋ฅผ ๋ณด์!
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';
// ์ปดํฌ๋ํธ๋ค
function Home() {
return (
<div>
<h1>ํ ํ์ด์ง ๐ </h1>
<nav>
<Link to="/about">์๊ฐ</Link> |
<Link to="/user/123">์ฌ์ฉ์ ํ๋กํ</Link>
</nav>
</div>
);
}
function About() {
return <h1>์๊ฐ ํ์ด์ง ๐ฅ</h1>;
}
function UserProfile() {
const { id } = useParams();
return (
<div>
<h1>์ฌ์ฉ์ ํ๋กํ ๐ค</h1>
<p>์ฌ์ฉ์ ID: {id}</p>
</div>
);
}
function NotFound() {
return <h1>404 - ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค ๐ข</h1>;
}
// ์ฑ ์ปดํฌ๋ํธ
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/user/:id" element={<UserProfile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Vue Router ์์
Vue.js๋ฅผ ์ด๋ค๋ฉด Vue Router! ์ด๊ฒ๋ ์ ๋ง ์ง๊ด์ ์ด์ผ.
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
import UserProfile from './components/UserProfile.vue';
// ๋ผ์ฐํธ ์ ์
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: { title: 'ํ ํ์ด์ง' }
},
{
path: '/about',
name: 'About',
component: About,
meta: { title: '์๊ฐ' }
},
{
path: '/user/:id',
name: 'UserProfile',
component: UserProfile,
meta: { title: '์ฌ์ฉ์ ํ๋กํ' }
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('./components/NotFound.vue')
}
];
// ๋ผ์ฐํฐ ์์ฑ
const router = createRouter({
history: createWebHistory(),
routes
});
// ๋ค๋น๊ฒ์ด์
๊ฐ๋
router.beforeEach((to, from, next) => {
// ํ์ด์ง ํ์ดํ ์ค์
document.title = to.meta.title || '๋ด ์ฑ';
// ์ธ์ฆ ์ฒดํฌ ์์
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login');
} else {
next();
}
});
export default router;
๐ฏ ๋ค๋น๊ฒ์ด์ ํจํด๊ณผ UX
๋ผ์ฐํ ๋ง ์ ๊ตฌํํ๋ค๊ณ ๋์ด ์๋์ผ. ์ฌ์ฉ์ ๊ฒฝํ(UX)์ ๊ณ ๋ คํ ๋ค๋น๊ฒ์ด์ ํจํด๋ ์ค์ํด!
1. ๋ก๋ฉ ์ํ ํ์
ํ์ด์ง ์ ํ ์ ๋ก๋ฉ ์ธ๋์ผ์ดํฐ๋ฅผ ๋ณด์ฌ์ฃผ๋ฉด ์ฌ์ฉ์๊ฐ ๋ญ๊ฐ ์งํ๋๊ณ ์๋ค๋ ๊ฑธ ์ ์ ์์ด.
class RouterWithLoading extends AdvancedRouter {
async render(component, params = {}, query = {}) {
const app = document.getElementById('app');
// ๋ก๋ฉ ํ์
this.showLoading();
try {
if (typeof component === 'function') {
const result = component({ params, query, router: this });
if (result instanceof Promise) {
const html = await result;
app.innerHTML = html;
} else {
app.innerHTML = result;
}
} else {
app.innerHTML = component;
}
} catch (error) {
console.error('๋ ๋๋ง ์๋ฌ:', error);
app.innerHTML = '<h1>์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค ๐ข</h1>';
} finally {
// ๋ก๋ฉ ์จ๊ธฐ๊ธฐ
this.hideLoading();
}
}
showLoading() {
let loader = document.getElementById('page-loader');
if (!loader) {
loader = document.createElement('div');
loader.id = 'page-loader';
loader.innerHTML = `
<div style="
position: fixed;
top: 0;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, #667eea, #764ba2);
animation: loading 1s ease-in-out infinite;
z-index: 9999;
"></div>
<style>
@keyframes loading {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
</style>
`;
document.body.appendChild(loader);
}
loader.style.display = 'block';
}
hideLoading() {
const loader = document.getElementById('page-loader');
if (loader) {
loader.style.display = 'none';
}
}
}
2. ํ์ด์ง ์ ํ ์ ๋๋ฉ์ด์
๋ถ๋๋ฌ์ด ์ ํ ํจ๊ณผ๋ฅผ ์ถ๊ฐํ๋ฉด ํจ์ฌ ์ธ๋ จ๋๊ฒ ๋ณด์ฌ!
// CSS ์ ํ ํจ๊ณผ
const styles = `
.page-transition {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.page-transition-out {
animation: fadeOut 0.2s ease-in-out;
}
@keyframes fadeOut {
from {
opacity: 1;
transform: translateY(0);
}
to {
opacity: 0;
transform: translateY(-20px);
}
}
`;
// ์คํ์ผ ์ถ๊ฐ
const styleSheet = document.createElement('style');
styleSheet.textContent = styles;
document.head.appendChild(styleSheet);
// ๋ผ์ฐํฐ์ ์ ๋๋ฉ์ด์
์ถ๊ฐ
class AnimatedRouter extends RouterWithLoading {
async render(component, params = {}, query = {}) {
const app = document.getElementById('app');
// ํ์ด๋ ์์
app.classList.add('page-transition-out');
await new Promise(resolve => setTimeout(resolve, 200));
// ์ฝํ
์ธ ๋ณ๊ฒฝ
await super.render(component, params, query);
// ํ์ด๋ ์ธ
app.classList.remove('page-transition-out');
app.classList.add('page-transition');
setTimeout(() => {
app.classList.remove('page-transition');
}, 300);
}
}
3. ๋ธ๋ ๋ํฌ๋ผ(Breadcrumb) ๋ค๋น๊ฒ์ด์
์ฌ์ฉ์๊ฐ ํ์ฌ ์ด๋์ ์๋์ง ์๋ ค์ฃผ๋ ๋ธ๋ ๋ํฌ๋ผ๋ ์ค์ํด!
function generateBreadcrumb(path) {
const parts = path.split('/').filter(p => p);
let breadcrumb = '<nav class="breadcrumb">';
breadcrumb += '<a href="/" data-link>๐ ํ</a>';
let currentPath = '';
for (let i = 0; i < parts.length; i++) {
currentPath += '/' + parts[i];
const isLast = i === parts.length - 1;
if (isLast) {
breadcrumb += ` > <span>${parts[i]}</span>`;
} else {
breadcrumb += ` > <a href="${currentPath}" data-link>${parts[i]}</a>`;
}
}
breadcrumb += '</nav>';
return breadcrumb;
}
// ์ฌ์ฉ ์์
const routes = {
'/products/category/electronics': {
component: ({ params }) => `
${generateBreadcrumb('/products/category/electronics')}
<h1>์ ์์ ํ ์นดํ
๊ณ ๋ฆฌ ๐ฑ</h1>
<p>๋ค์ํ ์ ์์ ํ์ ๋ง๋๋ณด์ธ์!</p>
`
}
};
4. ์คํฌ๋กค ๋ณต์
๋ค๋ก ๊ฐ๊ธฐ ํ์ ๋ ์ด์ ์คํฌ๋กค ์์น๋ก ๋์๊ฐ๋ฉด ์ฌ์ฉ์ ๊ฒฝํ์ด ์ข์์ ธ!
class ScrollRestorationRouter extends AnimatedRouter {
constructor(routes, options = {}) {
super(routes, options);
this.scrollPositions = new Map();
}
async handleRoute(path) {
// ํ์ฌ ์คํฌ๋กค ์์น ์ ์ฅ
if (this.currentPath) {
this.scrollPositions.set(this.currentPath, window.scrollY);
}
await super.handleRoute(path);
// ์คํฌ๋กค ์์น ๋ณต์ (๋ค๋ก ๊ฐ๊ธฐ์ธ ๊ฒฝ์ฐ)
if (this.scrollPositions.has(path)) {
setTimeout(() => {
window.scrollTo(0, this.scrollPositions.get(path));
}, 100);
} else {
// ์ ํ์ด์ง๋ ๋งจ ์๋ก
window.scrollTo(0, 0);
}
}
}
๐จ UX ์ฒดํฌ๋ฆฌ์คํธ
โ ๋ก๋ฉ ์ํ ํ์
โ ๋ถ๋๋ฌ์ด ํ์ด์ง ์ ํ
โ ๋ช ํํ ๋ค๋น๊ฒ์ด์ (๋ธ๋ ๋ํฌ๋ผ, ๋ฉ๋ด ํ์ด๋ผ์ดํธ)
โ ์คํฌ๋กค ์์น ๊ด๋ฆฌ
โ ์๋ฌ ์ฒ๋ฆฌ (404, ๋คํธ์ํฌ ์ค๋ฅ)
โ ์ ๊ทผ์ฑ (ํค๋ณด๋ ๋ค๋น๊ฒ์ด์ , ์คํฌ๋ฆฐ ๋ฆฌ๋)
โ ๋ชจ๋ฐ์ผ ์ต์ ํ
๐ ๋ณด์๊ณผ ์ธ์ฆ
SPA์์ ๋ผ์ฐํ ์ ๊ตฌํํ ๋ ๋ณด์๋ ์ ๊ฒฝ ์จ์ผ ํด! ํนํ ์ธ์ฆ์ด ํ์ํ ํ์ด์ง ์ฒ๋ฆฌ๊ฐ ์ค์ํ์ง.
์ธ์ฆ ๊ฐ๋ ๊ตฌํ
// ๊ฐ๋จํ ์ธ์ฆ ๊ด๋ฆฌ์
class AuthManager {
constructor() {
this.token = localStorage.getItem('authToken');
this.user = null;
}
isAuthenticated() {
return !!this.token;
}
async login(username, password) {
try {
// ์ค์ ๋ก๋ API ํธ์ถ
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.token) {
this.token = data.token;
this.user = data.user;
localStorage.setItem('authToken', data.token);
return true;
}
return false;
} catch (error) {
console.error('๋ก๊ทธ์ธ ์๋ฌ:', error);
return false;
}
}
logout() {
this.token = null;
this.user = null;
localStorage.removeItem('authToken');
}
getUser() {
return this.user;
}
}
const auth = new AuthManager();
// ๋ผ์ฐํฐ์ ์ธ์ฆ ๊ฐ๋ ์ถ๊ฐ
const protectedRoutes = {
'/': {
component: () => `
<h1>ํ ํ์ด์ง ๐ </h1>
<a href="/dashboard" data-link>๋์๋ณด๋ (๋ก๊ทธ์ธ ํ์)</a>
`
},
'/login': {
component: () => `
<div class="login-page">
<h1>๋ก๊ทธ์ธ ๐</h1>
<form id="loginForm">
<input type="text" id="username" placeholder="์ฌ์ฉ์๋ช
" required>
<input type="password" id="password" placeholder="๋น๋ฐ๋ฒํธ" required>
<button type="submit">๋ก๊ทธ์ธ</button>
</form>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const success = await auth.login(username, password);
if (success) {
router.navigate('/dashboard');
} else {
alert('๋ก๊ทธ์ธ ์คํจ!');
}
});
</script>
`
},
'/dashboard': {
component: () => {
const user = auth.getUser();
return `
<div class="dashboard">
<h1>๋์๋ณด๋ ๐</h1>
<p>ํ์ํฉ๋๋ค, ${user?.name || '์ฌ์ฉ์'}๋!</p>
<button onclick="auth.logout(); router.navigate('/');">
๋ก๊ทธ์์
</button>
</div>
`;
},
meta: {
requiresAuth: true
}
},
'/admin': {
component: () => `
<div class="admin-page">
<h1>๊ด๋ฆฌ์ ํ์ด์ง ๐</h1>
<p>๊ด๋ฆฌ์ ์ ์ฉ ํ์ด์ง์
๋๋ค.</p>
</div>
`,
meta: {
requiresAuth: true,
requiresAdmin: true
}
}
};
const router = new AdvancedRouter(protectedRoutes);
// ์ธ์ฆ ๊ฐ๋
router.beforeEach((to, from) => {
const route = protectedRoutes[to];
if (route?.meta?.requiresAuth) {
if (!auth.isAuthenticated()) {
alert('๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค!');
return '/login';
}
if (route.meta.requiresAdmin) {
const user = auth.getUser();
if (!user?.isAdmin) {
alert('๊ด๋ฆฌ์ ๊ถํ์ด ํ์ํฉ๋๋ค!');
return '/';
}
}
}
return true;
});
1. ํด๋ผ์ด์ธํธ ์ธก ์ธ์ฆ๋ง์ผ๋ก๋ ๋ถ์กฑํด! ์๋ฒ์์๋ ๋ฐ๋์ ๊ถํ์ ์ฒดํฌํด์ผ ํด.
2. ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ ํด๋ผ์ด์ธํธ์ ์ ์ฅํ์ง ๋ง! ํ ํฐ๋ง ์ ์ฅํ๊ณ ํ์ํ ๋ ์๋ฒ์์ ๊ฐ์ ธ์.
3. HTTPS๋ฅผ ์ฌ์ฉํด! ํ ํฐ์ด ์ค๊ฐ์ ํ์ทจ๋๋ฉด ํฐ์ผ๋.
4. ํ ํฐ ๋ง๋ฃ๋ฅผ ๊ตฌํํด! ์๊ตฌ์ ์ธ ํ ํฐ์ ์ํํด.
โก ์ฑ๋ฅ ์ต์ ํ
SPA๋ ์ด๊ธฐ ๋ก๋ฉ์ด ๋๋ฆด ์ ์์ด. ํ์ง๋ง ๋ช ๊ฐ์ง ๊ธฐ๋ฒ์ผ๋ก ์์ฒญ๋๊ฒ ๋น ๋ฅด๊ฒ ๋ง๋ค ์ ์์ด!
1. ์ฝ๋ ์คํ๋ฆฌํ (Code Splitting)
๋ชจ๋ ์ฝ๋๋ฅผ ํ ๋ฒ์ ๋ก๋ํ์ง ๋ง๊ณ , ํ์ํ ๋๋ง ๋ก๋ํ์!
// ๋์ import๋ฅผ ์ฌ์ฉํ ์ฝ๋ ์คํ๋ฆฌํ
const routes = {
'/': {
component: () => import('./pages/Home.js').then(m => m.default())
},
'/about': {
component: async () => {
const module = await import('./pages/About.js');
return module.default();
}
},
'/heavy-page': {
// ๋ฌด๊ฑฐ์ด ํ์ด์ง๋ ํ์ํ ๋๋ง ๋ก๋
component: async () => {
const [pageModule, chartModule] = await Promise.all([
import('./pages/HeavyPage.js'),
import('./lib/charts.js')
]);
return pageModule.default(chartModule);
}
}
};
// Webpack์ด๋ Vite ๊ฐ์ ๋ฒ๋ค๋ฌ๊ฐ ์๋์ผ๋ก ์ฒญํฌ๋ฅผ ๋ถ๋ฆฌํด์ค!
2. ํ๋ฆฌํ์นญ (Prefetching)
์ฌ์ฉ์๊ฐ ํด๋ฆญํ๊ธฐ ์ ์ ๋ฏธ๋ฆฌ ๋ก๋ํด๋๋ฉด ๋ ๋น ๋ฅด๊ฒ ๋๊ปด์ ธ!
class PrefetchRouter extends AdvancedRouter {
constructor(routes, options = {}) {
super(routes, options);
this.prefetchedRoutes = new Set();
this.setupPrefetch();
}
setupPrefetch() {
// ๋งํฌ์ ๋ง์ฐ์ค๋ฅผ ์ฌ๋ฆฌ๋ฉด ํ๋ฆฌํ์น
document.addEventListener('mouseover', (e) => {
if (e.target.matches('[data-link]')) {
const href = e.target.getAttribute('href');
this.prefetch(href);
}
});
// Intersection Observer๋ก ๋ทฐํฌํธ์ ๋ค์ด์ค๋ฉด ํ๋ฆฌํ์น
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const href = entry.target.getAttribute('href');
this.prefetch(href);
}
});
});
// data-prefetch ์์ฑ์ด ์๋ ๋งํฌ ๊ด์ฐฐ
document.querySelectorAll('[data-prefetch]').forEach(link => {
observer.observe(link);
});
}
async prefetch(path) {
if (this.prefetchedRoutes.has(path)) {
return; // ์ด๋ฏธ ํ๋ฆฌํ์น๋จ
}
const route = this.routes[path];
if (route && typeof route.component === 'function') {
try {
// ์ปดํฌ๋ํธ๋ฅผ ๋ฏธ๋ฆฌ ๋ก๋ (๋ ๋๋ง์ ํ์ง ์์)
const component = route.component;
if (component.constructor.name === 'AsyncFunction') {
await component({ params: {}, query: {} });
}
this.prefetchedRoutes.add(path);
console.log(`โ
${path} ํ๋ฆฌํ์น ์๋ฃ`);
} catch (error) {
console.error(`ํ๋ฆฌํ์น ์คํจ: ${path}`, error);
}
}
}
}
// ์ฌ์ฉ ์์
const routes = {
'/': {
component: () => `
<h1>ํ ํ์ด์ง</h1>
<!-- ๋ง์ฐ์ค ์ค๋ฒ ์ ํ๋ฆฌํ์น -->
<a href="/about" data-link>์๊ฐ</a>
<!-- ๋ทฐํฌํธ์ ๋ค์ด์ค๋ฉด ํ๋ฆฌํ์น -->
<a href="/products" data-link data-prefetch>์ ํ ๋ชฉ๋ก</a>
`
}
};
3. ์บ์ฑ ์ ๋ต
ํ ๋ฒ ๋ก๋ํ ๋ฐ์ดํฐ๋ ์บ์์ ์ ์ฅํด์ ์ฌ์ฌ์ฉํ์!
class CachedRouter extends PrefetchRouter {
constructor(routes, options = {}) {
super(routes, options);
this.cache = new Map();
this.cacheTimeout = options.cacheTimeout || 5 * 60 * 1000; // 5๋ถ
}
async fetchData(url, options = {}) {
const cacheKey = url + JSON.stringify(options);
// ์บ์ ํ์ธ
if (this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
// ์บ์๊ฐ ์ ํจํ์ง ํ์ธ
if (Date.now() - cached.timestamp < this.cacheTimeout) {
console.log('๐พ ์บ์์์ ๋ก๋:', url);
return cached.data;
} else {
// ๋ง๋ฃ๋ ์บ์ ์ญ์
this.cache.delete(cacheKey);
}
}
// ์๋ก fetch
console.log('๐ ์๋ฒ์์ ๋ก๋:', url);
const response = await fetch(url, options);
const data = await response.json();
// ์บ์์ ์ ์ฅ
this.cache.set(cacheKey, {
data,
timestamp: Date.now()
});
return data;
}
clearCache(pattern) {
if (pattern) {
// ํจํด๊ณผ ์ผ์นํ๋ ์บ์๋ง ์ญ์
for (let key of this.cache.keys()) {
if (key.includes(pattern)) {
this.cache.delete(key);
}
}
} else {
// ์ ์ฒด ์บ์ ์ญ์
this.cache.clear();
}
}
}
// ์ฌ์ฉ ์์
const router = new CachedRouter(routes);
// ๋ฐ์ดํฐ fetch (์๋์ผ๋ก ์บ์ฑ๋จ)
const products = await router.fetchData('/api/products');
// ํน์ ์บ์ ์ญ์
router.clearCache('/api/products');
4. ๊ฐ์ ์คํฌ๋กค๋ง
๊ธด ๋ชฉ๋ก์ ๋ ๋๋งํ ๋๋ ๊ฐ์ ์คํฌ๋กค๋ง์ ์ฌ์ฉํ๋ฉด ์ฑ๋ฅ์ด ์์ฒญ ์ข์์ ธ!
class VirtualList {
constructor(container, items, itemHeight, renderItem) {
this.container = container;
this.items = items;
this.itemHeight = itemHeight;
this.renderItem = renderItem;
this.visibleStart = 0;
this.visibleEnd = 0;
this.init();
}
init() {
// ์ปจํ
์ด๋ ๋์ด ๊ณ์ฐ
const containerHeight = this.container.clientHeight;
const visibleCount = Math.ceil(containerHeight / this.itemHeight) + 1;
// ์คํฌ๋กค ์ด๋ฒคํธ
this.container.addEventListener('scroll', () => {
this.update();
});
// ์ด๊ธฐ ๋ ๋๋ง
this.update();
}
update() {
const scrollTop = this.container.scrollTop;
const containerHeight = this.container.clientHeight;
// ๋ณด์ด๋ ๋ฒ์ ๊ณ์ฐ
this.visibleStart = Math.floor(scrollTop / this.itemHeight);
this.visibleEnd = Math.ceil((scrollTop + containerHeight) / this.itemHeight);
// ๋ฒํผ ์ถ๊ฐ (๋ถ๋๋ฌ์ด ์คํฌ๋กค์ ์ํด)
const buffer = 3;
this.visibleStart = Math.max(0, this.visibleStart - buffer);
this.visibleEnd = Math.min(this.items.length, this.visibleEnd + buffer);
this.render();
}
render() {
const visibleItems = this.items.slice(this.visibleStart, this.visibleEnd);
// ์ ์ฒด ๋์ด ์ค์ (์คํฌ๋กค๋ฐ๋ฅผ ์ํด)
const totalHeight = this.items.length * this.itemHeight;
let html = `<div style="height: ${totalHeight}px; position: relative;">`;
visibleItems.forEach((item, index) => {
const actualIndex = this.visibleStart + index;
const top = actualIndex * this.itemHeight;
html += `
<div style="
position: absolute;
top: ${top}px;
height: ${this.itemHeight}px;
width: 100%;
">
${this.renderItem(item, actualIndex)}
</div>
`;
});
html += '</div>';
this.container.innerHTML = html;
}
}
// ์ฌ์ฉ ์์
const routes = {
'/products': {
component: async () => {
const products = await fetch('/api/products').then(r => r.json());
// 10,000๊ฐ ์์ดํ
๋ ๋ถ๋๋ฝ๊ฒ!
setTimeout(() => {
const container = document.getElementById('product-list');
new VirtualList(container, products, 80, (product, index) => `
<div class="product-item">
<h3>${product.name}</h3>
<p>${product.price}์</p>
</div>
`);
}, 0);
return `
<h1>์ ํ ๋ชฉ๋ก (${products.length}๊ฐ)</h1>
<div id="product-list" style="height: 600px; overflow-y: auto;">
๋ก๋ฉ ์ค...
</div>
`;
}
}
};
โก ์ฑ๋ฅ ์ต์ ํ ์ฒดํฌ๋ฆฌ์คํธ
โ ์ฝ๋ ์คํ๋ฆฌํ ์ผ๋ก ์ด๊ธฐ ๋ก๋ฉ ์ต์ํ
โ ํ๋ฆฌํ์นญ์ผ๋ก ์ฒด๊ฐ ์๋ ํฅ์
โ ์บ์ฑ์ผ๋ก ๋ถํ์ํ ๋คํธ์ํฌ ์์ฒญ ์ ๊ฑฐ
โ ๊ฐ์ ์คํฌ๋กค๋ง์ผ๋ก ๋๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
โ ์ด๋ฏธ์ง ๋ ์ด์ง ๋ก๋ฉ
โ ๋ฒ๋ค ํฌ๊ธฐ ์ต์ํ (Tree shaking)
โ CDN ํ์ฉ
๐งช ํ ์คํ ๊ณผ ๋๋ฒ๊น
๋ผ์ฐํฐ๋ฅผ ๋ง๋ค์์ผ๋ฉด ์ ๋๋ก ์๋ํ๋์ง ํ ์คํธํด์ผ๊ฒ ์ง? ํ ์คํ ์ ๋ต์ ์์๋ณด์!
1. ์ ๋ ํ ์คํธ
// Jest๋ฅผ ์ฌ์ฉํ ๋ผ์ฐํฐ ํ
์คํธ
describe('Router', () => {
let router;
beforeEach(() => {
// DOM ์ด๊ธฐํ
document.body.innerHTML = '<div id="app"></div>';
// ๋ผ์ฐํฐ ์์ฑ
router = new AdvancedRouter({
'/': { component: () => 'Home' },
'/about': { component: () => 'About' },
'/user/:id': { component: ({ params }) => `User ${params.id}` }
});
});
test('๊ธฐ๋ณธ ๊ฒฝ๋ก ๋ ๋๋ง', () => {
router.handleRoute('/');
expect(document.getElementById('app').innerHTML).toBe('Home');
});
test('๋์ ํ๋ผ๋ฏธํฐ ํ์ฑ', () => {
router.handleRoute('/user/123');
expect(document.getElementById('app').innerHTML).toBe('User 123');
});
test('์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ํ์ฑ', () => {
router.handleRoute('/search?q=test&sort=latest');
expect(router.query).toEqual({ q: 'test', sort: 'latest' });
});
test('404 ์ฒ๋ฆฌ', () => {
router.handleRoute('/nonexistent');
expect(document.getElementById('app').innerHTML).toContain('404');
});
test('๋ค๋น๊ฒ์ด์
๊ฐ๋', async () => {
let guardCalled = false;
router.beforeEach(() => {
guardCalled = true;
return false; // ๋ค๋น๊ฒ์ด์
์ทจ์
});
await router.handleRoute('/about');
expect(guardCalled).toBe(true);
expect(document.getElementById('app').innerHTML).not.toBe('About');
});
});
2. E2E ํ ์คํธ
// Cypress๋ฅผ ์ฌ์ฉํ E2E ํ
์คํธ
describe('SPA Navigation', () => {
beforeEach(() => {
cy.visit('/');
});
it('ํ์์ ์๊ฐ ํ์ด์ง๋ก ์ด๋', () => {
cy.contains('์๊ฐ').click();
cy.url().should('include', '/about');
cy.contains('์๊ฐ ํ์ด์ง').should('be.visible');
});
it('๋ค๋ก ๊ฐ๊ธฐ ๋ฒํผ ์๋', () => {
cy.contains('์๊ฐ').click();
cy.go('back');
cy.url().should('eq', Cypress.config().baseUrl + '/');
});
it('์ง์ URL ์
๋ ฅ', () => {
cy.visit('/user/123');
cy.contains('์ฌ์ฉ์ ID: 123').should('be.visible');
});
it('์ธ์ฆ ๊ฐ๋', () => {
cy.visit('/dashboard');
cy.url().should('include', '/login');
cy.contains('๋ก๊ทธ์ธ').should('be.visible');
});
it('ํ์ด์ง ์ ํ ์ ๋๋ฉ์ด์
', () => {
cy.contains('์๊ฐ').click();
cy.get('#app').should('have.class', 'page-transition');
});
});
3. ๋๋ฒ๊น ๋๊ตฌ
// ๋ผ์ฐํฐ ๋๋ฒ๊น
ํ๋ฌ๊ทธ์ธ
class RouterDebugger {
constructor(router) {
this.router = router;
this.logs = [];
this.enabled = true;
this.attachDebugger();
}
attachDebugger() {
// ๋ค๋น๊ฒ์ด์
๋ก๊น
this.router.beforeEach((to, from) => {
if (this.enabled) {
const log = {
type: 'navigation',
from,
to,
timestamp: new Date().toISOString(),
params: this.router.params,
query: this.router.query
};
this.logs.push(log);
console.log('๐ [Router Debug]', log);
}
return true;
});
// ์๋ฌ ๋ก๊น
const originalRender = this.router.render.bind(this.router);
this.router.render = async (...args) => {
try {
await originalRender(...args);
} catch (error) {
const log = {
type: 'error',
error: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
};
this.logs.push(log);
console.error('โ [Router Error]', log);
throw error;
}
};
}
// ๋๋ฒ๊ทธ ํจ๋ ํ์
showDebugPanel() {
const panel = document.createElement('div');
panel.id = 'router-debug-panel';
panel.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
width: 400px;
max-height: 500px;
background: white;
border: 2px solid #667eea;
border-radius: 12px;
padding: 15px;
overflow-y: auto;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 10000;
font-family: monospace;
font-size: 12px;
`;
let html = `
<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
<strong>๐ Router Debug</strong>
<button onclick="document.getElementById('router-debug-panel').remove()">โ</button>
</div>
<div>
<strong>Current Route:</strong> ${this.router.currentPath}<br>
<strong>Params:</strong> ${JSON.stringify(this.router.params)}<br>
<strong>Query:</strong> ${JSON.stringify(this.router.query)}
</div>
<hr>
<div><strong>Navigation History:</strong></div>
`;
this.logs.slice(-10).reverse().forEach(log => {
const color = log.type === 'error' ? '#ef4444' : '#667eea';
html += `
<div style="margin: 5px 0; padding: 5px; background: #f3f4f6; border-radius: 4px;">
<div style="color: ${color}; font-weight: bold;">${log.type.toUpperCase()}</div>
<div>${log.from || ''} โ ${log.to || ''}</div>
<div style="font-size: 10px; color: #6b7280;">${log.timestamp}</div>
</div>
`;
});
panel.innerHTML = html;
document.body.appendChild(panel);
}
// ๋ก๊ทธ ๋ด๋ณด๋ด๊ธฐ
exportLogs() {
const dataStr = JSON.stringify(this.logs, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = `router-logs-${Date.now()}.json`;
link.click();
}
// ์ฑ๋ฅ ๋ถ์
analyzePerformance() {
const navigationLogs = this.logs.filter(l => l.type === 'navigation');
return {
totalNavigations: navigationLogs.length,
averageTime: '๊ณ์ฐ ํ์',
mostVisited: this.getMostVisitedRoute(navigationLogs),
errorRate: (this.logs.filter(l => l.type === 'error').length / this.logs.length * 100).toFixed(2) + '%'
};
}
getMostVisitedRoute(logs) {
const counts = {};
logs.forEach(log => {
counts[log.to] = (counts[log.to] || 0) + 1;
});
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'N/A';
}
}
// ์ฌ์ฉ ์์
const router = new AdvancedRouter(routes);
const debugger = new RouterDebugger(router);
// ๊ฐ๋ฐ ๋ชจ๋์์๋ง ๋๋ฒ๊ทธ ํจ๋ ํ์
if (process.env.NODE_ENV === 'development') {
// Ctrl+Shift+D๋ก ๋๋ฒ๊ทธ ํจ๋ ํ ๊ธ
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.shiftKey && e.key === 'D') {
debugger.showDebugPanel();
}
});
}
โข Chrome DevTools์ Network ํญ์์ ๋ผ์ฐํธ ๋ณ๊ฒฝ ์ ๋คํธ์ํฌ ์์ฒญ ํ์ธ
โข React DevTools๋ Vue DevTools ๊ฐ์ ํ๋ ์์ํฌ ์ ์ฉ ๋๊ตฌ ํ์ฉ
โข Performance ํญ์ผ๋ก ๋ ๋๋ง ์ฑ๋ฅ ๋ถ์
โข Console์ ๋ผ์ฐํธ ๋ณ๊ฒฝ ๋ก๊ทธ ๋จ๊ธฐ๊ธฐ
๐ SEO์ ๋ฉํ ํ๊ทธ ๊ด๋ฆฌ
SPA์ ๊ฐ์ฅ ํฐ ์ฝ์ ์ด SEO์ผ. ํ์ง๋ง ์ ๋๋ก ์ฒ๋ฆฌํ๋ฉด ๋ฌธ์ ์์ด!
1. ๋์ ๋ฉํ ํ๊ทธ ๊ด๋ฆฌ
class SEOManager {
constructor() {
this.defaultMeta = {
title: '๋ด ๋ฉ์ง SPA',
description: 'JavaScript๋ก ๋ง๋ ์ฑ๊ธ ํ์ด์ง ์ ํ๋ฆฌ์ผ์ด์
',
keywords: 'SPA, JavaScript, ๋ผ์ฐํ
',
ogImage: '/images/og-default.jpg',
ogType: 'website'
};
}
updateMeta(meta = {}) {
const finalMeta = { ...this.defaultMeta, ...meta };
// ํ์ด์ง ํ์ดํ
document.title = finalMeta.title;
// ๋ฉํ ํ๊ทธ ์
๋ฐ์ดํธ
this.setMetaTag('description', finalMeta.description);
this.setMetaTag('keywords', finalMeta.keywords);
// Open Graph ํ๊ทธ (์์
๋ฏธ๋์ด ๊ณต์ ์ฉ)
this.setMetaTag('og:title', finalMeta.title, 'property');
this.setMetaTag('og:description', finalMeta.description, 'property');
this.setMetaTag('og:image', finalMeta.ogImage, 'property');
this.setMetaTag('og:type', finalMeta.ogType, 'property');
this.setMetaTag('og:url', window.location.href, 'property');
// Twitter ์นด๋
this.setMetaTag('twitter:card', 'summary_large_image', 'name');
this.setMetaTag('twitter:title', finalMeta.title, 'name');
this.setMetaTag('twitter:description', finalMeta.description, 'name');
this.setMetaTag('twitter:image', finalMeta.ogImage, 'name');
// Canonical URL
this.setCanonicalURL(window.location.href);
}
setMetaTag(name, content, attribute = 'name') {
let element = document.querySelector(`meta[${attribute}="${name}"]`);
if (!element) {
element = document.createElement('meta');
element.setAttribute(attribute, name);
document.head.appendChild(element);
}
element.setAttribute('content', content);
}
setCanonicalURL(url) {
let link = document.querySelector('link[rel="canonical"]');
if (!link) {
link = document.createElement('link');
link.setAttribute('rel', 'canonical');
document.head.appendChild(link);
}
link.setAttribute('href', url);
}
// ๊ตฌ์กฐํ๋ ๋ฐ์ดํฐ (JSON-LD)
setStructuredData(data) {
let script = document.querySelector('script[type="application/ld+json"]');
if (!script) {
script = document.createElement('script');
script.type = 'application/ld+json';
document.head.appendChild(script);
}
script.textContent = JSON.stringify(data);
}
}
const seoManager = new SEOManager();
// ๋ผ์ฐํฐ์ SEO ํตํฉ
const routes = {
'/': {
component: () => '...',
meta: {
title: 'ํ - ์ฌ๋ฅ๋ท',
description: '๋ค์ํ ์ฌ๋ฅ์ ๊ณต์ ํ๊ณ ๊ฑฐ๋ํ๋ ํ๋ซํผ',
keywords: '์ฌ๋ฅ๊ณต์ , ํ๋ฆฌ๋์, ์ธ์ฃผ',
ogImage: '/images/home-og.jpg'
}
},
'/blog/:slug': {
component: async ({ params }) => {
// ๋ธ๋ก๊ทธ ํฌ์คํธ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
const post = await fetch(`/api/posts/${params.slug}`).then(r => r.json());
// SEO ๋ฉํ ์
๋ฐ์ดํธ
seoManager.updateMeta({
title: `${post.title} - ์ฌ๋ฅ๋ท ๋ธ๋ก๊ทธ`,
description: post.excerpt,
keywords: post.tags.join(', '),
ogImage: post.coverImage,
ogType: 'article'
});
// ๊ตฌ์กฐํ๋ ๋ฐ์ดํฐ ์ถ๊ฐ
seoManager.setStructuredData({
'@context': 'https://schema.org',
'@type': 'BlogPosting',
'headline': post.title,
'image': post.coverImage,
'datePublished': post.publishedAt,
'dateModified': post.updatedAt,
'author': {
'@type': 'Person',
'name': post.author.name
},
'publisher': {
'@type': 'Organization',
'name': '์ฌ๋ฅ๋ท',
'logo': {
'@type': 'ImageObject',
'url': 'https://www.jaenung.net/logo.png'
}
},
'description': post.excerpt
});
return `
<article>
<h1>${post.title}</h1>
<div>${post.content}</div>
</article>
`;
}
}
};
// ๋ผ์ฐํฐ์ SEO ํ
์ถ๊ฐ
router.afterEach((to) => {
const route = routes[to];
if (route?.meta) {
seoManager.updateMeta(route.meta);
}
});
2. ์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง (SSR)
์ง์ง ์๋ฒฝํ SEO๋ฅผ ์ํ๋ค๋ฉด SSR์ ๊ณ ๋ คํด๋ด!
// Node.js + Express๋ก SSR ๊ตฌํ
const express = require('express');
const app = express();
// ๋ผ์ฐํธ๋ณ ๋ ๋๋ง ํจ์
const renderPage = (route, data = {}) => {
const routes = {
'/': () => `
<!DOCTYPE html>
<html>
<head>
<title>ํ - ์ฌ๋ฅ๋ท</title>
<meta name="description" content="๋ค์ํ ์ฌ๋ฅ์ ๊ณต์ ํ์ธ์">
</head>
<body>
<div id="app">
<h1>ํ ํ์ด์ง</h1>
<p>์๋ฒ์์ ๋ ๋๋ง๋ ์ฝํ
์ธ </p>
</div>
<script src="/js/app.js"></script>
</body>
</html>
`,
'/blog/:slug': () => `
<!DOCTYPE html>
<html>
<head>
<title>${data.title} - ์ฌ๋ฅ๋ท ๋ธ๋ก๊ทธ</title>
<meta name="description" content="${data.excerpt}">
<meta property="og:title" content="${data.title}">
<meta property="og:image" content="${data.coverImage}">
</head>
<body>
<div id="app">
<article>
<h1>${data.title}</h1>
<div>${data.content}</div>
</article>
</div>
<script>
// ํด๋ผ์ด์ธํธ์์ hydration
window.__INITIAL_DATA__ = ${JSON.stringify(data)};
</script>
<script src="/js/app.js"></script>
</body>
</html>
`
};
const renderer = routes[route];
return renderer ? renderer() : routes['/']();
};
// ๋ผ์ฐํธ ํธ๋ค๋ฌ
app.get('/blog/:slug', async (req, res) => {
try {
// ๋ฐ์ดํฐ๋ฒ ์ด์ค์์ ํฌ์คํธ ๊ฐ์ ธ์ค๊ธฐ
const post = await getPostBySlug(req.params.slug);
if (!post) {
return res.status(404).send('ํฌ์คํธ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค');
}
// ์๋ฒ์์ HTML ๋ ๋๋ง
const html = renderPage('/blog/:slug', post);
res.send(html);
} catch (error) {
console.error(error);
res.status(500).send('์๋ฒ ์ค๋ฅ');
}
});
// ๊ธฐ๋ณธ ๋ผ์ฐํธ
app.get('*', (req, res) => {
const html = renderPage(req.path);
res.send(html);
});
app.listen(3000, () => {
console.log('SSR ์๋ฒ ์คํ ์ค! ๐');
});
SSR์ด ์ข์ ๊ฒฝ์ฐ:
โข SEO๊ฐ ๋งค์ฐ ์ค์ํ ๊ฒฝ์ฐ (๋ธ๋ก๊ทธ, ๋ด์ค, ์ด์ปค๋จธ์ค)
โข ์ด๊ธฐ ๋ก๋ฉ ์๋๊ฐ ์ค์ํ ๊ฒฝ์ฐ
โข ์์ ๋ฏธ๋์ด ๊ณต์ ๊ฐ ๋ง์ ๊ฒฝ์ฐ
CSR์ด ์ข์ ๊ฒฝ์ฐ:
โข ์ธํฐ๋์ ์ด ๋ง์ ์ฑ (๋์๋ณด๋, ๊ด๋ฆฌ์ ํ์ด์ง)
โข ๋ก๊ทธ์ธ ํ์๋ง ์ฌ์ฉํ๋ ์๋น์ค
โข ์๋ฒ ๋ฆฌ์์ค๊ฐ ์ ํ์ ์ธ ๊ฒฝ์ฐ
๐ฑ ๋ชจ๋ฐ์ผ ์ต์ ํ
๋ชจ๋ฐ์ผ์์๋ ์๋ฒฝํ๊ฒ ์๋ํ๋ ๋ค๋น๊ฒ์ด์ ์ ๋ง๋ค์ด๋ณด์!
1. ํฐ์น ์ ์ค์ฒ ์ง์
class TouchNavigationRouter extends AdvancedRouter {
constructor(routes, options = {}) {
super(routes, options);
this.setupTouchGestures();
}
setupTouchGestures() {
let touchStartX = 0;
let touchEndX = 0;
document.addEventListener('touchstart', (e) => {
touchStartX = e.changedTouches[0].screenX;
}, { passive: true });
document.addEventListener('touchend', (e) => {
touchEndX = e.changedTouches[0].screenX;
this.handleSwipe();
}, { passive: true });
}
handleSwipe() {
const swipeThreshold = 100;
const diff = touchStartX - touchEndX;
if (Math.abs(diff) > swipeThreshold) {
if (diff > 0) {
// ์ผ์ชฝ์ผ๋ก ์ค์์ดํ (์์ผ๋ก ๊ฐ๊ธฐ)
this.forward();
} else {
// ์ค๋ฅธ์ชฝ์ผ๋ก ์ค์์ดํ (๋ค๋ก ๊ฐ๊ธฐ)
this.back();
}
}
}
}
2. ๋ชจ๋ฐ์ผ ๋ฉ๋ด
// ๋ฐ์ํ ๋ค๋น๊ฒ์ด์
์ปดํฌ๋ํธ
function createMobileNav() {
return `
<style>
.mobile-nav {
position: fixed;
top: 0;
left: -100%;
width: 80%;
max-width: 300px;
height: 100vh;
background: white;
box-shadow: 2px 0 10px rgba(0,0,0,0.1);
transition: left 0.3s ease;
z-index: 1000;
}
.mobile-nav.open {
left: 0;
}
.mobile-nav-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background: rgba(0,0,0,0.5);
display: none;
z-index: 999;
}
.mobile-nav-overlay.show {
display: block;
}
.hamburger {
display: none;
position: fixed;
top: 20px;
left: 20px;
z-index: 1001;
background: white;
border: none;
padding: 10px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
cursor: pointer;
}
@media (max-width: 768px) {
.hamburger {
display: block;
}
.desktop-nav {
display: none;
}
}
</style>
<button class="hamburger" onclick="toggleMobileNav()">
โฐ
</button>
<div class="mobile-nav-overlay" onclick="toggleMobileNav()"></div>
<nav class="mobile-nav">
<div style="padding: 20px;">
<h2>๋ฉ๋ด</h2>
<ul style="list-style: none; padding: 0;">
<li><a href="/" data-link onclick="toggleMobileNav()">ํ</a></li>
<li><a href="/about" data-link onclick="toggleMobileNav()">์๊ฐ</a></li>
<li><a href="/products" data-link onclick="toggleMobileNav()">์ ํ</a></li>
<li><a href="/contact" data-link onclick="toggleMobileNav()">์ฐ๋ฝ์ฒ</a></li>
</ul>
</div>
</nav>
<script>
function toggleMobileNav() {
const nav = document.querySelector('.mobile-nav');
const overlay = document.querySelector('.mobile-nav-overlay');
nav.classList.toggle('open');
overlay.classList.toggle('show');
}
</script>
`;
}
3. PWA ์ง์
// Service Worker๋ก ์คํ๋ผ์ธ ์ง์
// sw.js
const CACHE_NAME = 'spa-cache-v1';
const urlsToCache = [
'/',
'/css/style.css',
'/js/app.js',
'/js/router.js'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
// ์บ์์ ์์ผ๋ฉด ์บ์์์, ์์ผ๋ฉด ๋คํธ์ํฌ์์
return response || fetch(event.request);
})
);
});
// ์ฑ์์ Service Worker ๋ฑ๋ก
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
console.log('โ
Service Worker ๋ฑ๋ก ์ฑ๊ณต!', registration);
})
.catch((error) => {
console.error('โ Service Worker ๋ฑ๋ก ์คํจ:', error);
});
}
๐ ์ค์ ํ๋ก์ ํธ: ์์ ํ SPA ๋ง๋ค๊ธฐ
์ง๊ธ๊น์ง ๋ฐฐ์ด ๋ชจ๋ ๊ฑธ ์ข ํฉํด์ ์ค์ ํ๋ก์ ํธ๋ฅผ ๋ง๋ค์ด๋ณด์! ๊ฐ๋จํ ๋ธ๋ก๊ทธ SPA๋ฅผ ๊ตฌํํ ๊ฒ.
// ์์ ํ ๋ธ๋ก๊ทธ SPA ๊ตฌํ
class BlogSPA {
constructor() {
this.router = null;
this.seoManager = new SEOManager();
this.auth = new AuthManager();
this.init();
}
init() {
// ๋ผ์ฐํธ ์ ์
const routes = {
'/': {
component: this.renderHome.bind(this),
meta: {
title: 'ํ - ๋ด ๋ธ๋ก๊ทธ',
description: 'JavaScript๋ก ๋ง๋ ๋ธ๋ก๊ทธ'
}
},
'/posts': {
component: this.renderPostList.bind(this),
meta: {
title: 'ํฌ์คํธ ๋ชฉ๋ก'
}
},
'/post/:slug': {
component: this.renderPost.bind(this)
},
'/write': {
component: this.renderEditor.bind(this),
meta: {
requiresAuth: true
}
},
'/login': {
component: this.renderLogin.bind(this)
},
'/404': {
component: () => this.render404()
}
};
// ๋ผ์ฐํฐ ์์ฑ
this.router = new AdvancedRouter(routes, { mode: 'history' });
// ์ธ์ฆ ๊ฐ๋
this.router.beforeEach((to, from) => {
const route = routes[to];
if (route?.meta?.requiresAuth && !this.auth.isAuthenticated()) {
alert('๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค!');
return '/login';
}
return true;
});
// SEO ์
๋ฐ์ดํธ
this.router.afterEach((to) => {
const route = routes[to];
if (route?.meta) {
this.seoManager.updateMeta(route.meta);
}
});
}
async renderHome() {
const recentPosts = await this.fetchRecentPosts();
return `
<div class="home-page">
${this.renderHeader()}
<section class="hero">
<h1>ํ์ํฉ๋๋ค! ๐</h1>
<p>JavaScript์ ์น ๊ฐ๋ฐ์ ๋ํ ์ด์ผ๊ธฐ๋ฅผ ๋๋๋๋ค.</p>
</section>
<section class="recent-posts">
<h2>์ต๊ทผ ํฌ์คํธ</h2>
<div class="post-grid">
${recentPosts.map(post => `
<article class="post-card">
<img src="${post.coverImage}" alt="${post.title}">
<h3><a href="/post/${post.slug}" data-link>${post.title}</a></h3>
<p>${post.excerpt}</p>
<div class="post-meta">
<span>${post.author}</span>
<span>${post.date}</span>
</div>
</article>
`).join('')}
</div>
</section>
${this.renderFooter()}
</div>
`;
}
async renderPostList({ query }) {
const page = parseInt(query.page) || 1;
const category = query.category || 'all';
const posts = await this.fetchPosts({ page, category });
return `
<div class="post-list-page">
${this.renderHeader()}
<div class="container">
<h1>ํฌ์คํธ ๋ชฉ๋ก</h1>
<div class="filters">
<a href="/posts?category=all" data-link>์ ์ฒด</a>
<a href="/posts?category=javascript" data-link>JavaScript</a>
<a href="/posts?category=css" data-link>CSS</a>
<a href="/posts?category=react" data-link>React</a>
</div>
<div class="posts">
${posts.map(post => `
<article>
<h2><a href="/post/${post.slug}" data-link>${post.title}</a></h2>
<p>${post.excerpt}</p>
<a href="/post/${post.slug}" data-link>๋ ์ฝ๊ธฐ โ</a>
</article>
`).join('')}
</div>
<div class="pagination">
${page > 1 ? `<a href="/posts?page=${page-1}&category=${category}" data-link>โ ์ด์ </a>` : ''}
<span>ํ์ด์ง ${page}</span>
<a href="/posts?page=${page+1}&category=${category}" data-link>๋ค์ โ</a>
</div>
</div>
${this.renderFooter()}
</div>
`;
}
async renderPost({ params }) {
const post = await this.fetchPost(params.slug);
if (!post) {
this.router.navigate('/404');
return;
}
// SEO ๋ฉํ ์
๋ฐ์ดํธ
this.seoManager.updateMeta({
title: `${post.title} - ๋ด ๋ธ๋ก๊ทธ`,
description: post.excerpt,
ogImage: post.coverImage,
ogType: 'article'
});
return `
<div class="post-page">
${this.renderHeader()}
<article class="post-content">
<header>
<h1>${post.title}</h1>
<div class="post-meta">
<span>์์ฑ์: ${post.author}</span>
<span>๋ ์ง: ${post.date}</span>
<span>์นดํ
๊ณ ๋ฆฌ: ${post.category}</span>
</div>
</header>
<img src="${post.coverImage}" alt="${post.title}" class="cover-image">
<div class="content">
${post.content}
</div>
<footer>
<div class="tags">
${post.tags.map(tag => `<span class="tag">#${tag}</span>`).join('')}
</div>
<div class="share">
<button onclick="sharePost('${post.slug}')">๊ณต์ ํ๊ธฐ ๐ค</button>
</div>
</footer>
</article>
<section class="comments">
<h2>๋๊ธ</h2>
<div id="comments-container"></div>
</section>
${this.renderFooter()}
</div>
`;
}
renderEditor() {
return `
<div class="editor-page">
${this.renderHeader()}
<div class="container">
<h1>์ ํฌ์คํธ ์์ฑ โ๏ธ</h1>
<form id="post-form">
<input type="text" id="title" placeholder="์ ๋ชฉ" required>
<input type="text" id="slug" placeholder="URL ์ฌ๋ฌ๊ทธ" required>
<select id="category">
<option value="javascript">JavaScript</option>
<option value="css">CSS</option>
<option value="react">React</option>
</select>
<textarea id="content" placeholder="๋ด์ฉ์ ์์ฑํ์ธ์..." rows="20"></textarea>
<input type="text" id="tags" placeholder="ํ๊ทธ (์ผํ๋ก ๊ตฌ๋ถ)">
<button type="submit">๋ฐํํ๊ธฐ</button>
</form>
</div>
${this.renderFooter()}
<script>
document.getElementById('post-form').addEventListener('submit', async (e) => {
e.preventDefault();
const post = {
title: document.getElementById('title').value,
slug: document.getElementById('slug').value,
category: document.getElementById('category').value,
content: document.getElementById('content').value,
tags: document.getElementById('tags').value.split(',').map(t => t.trim())
};
const success = await blogSPA.savePost(post);
if (success) {
alert('ํฌ์คํธ๊ฐ ๋ฐํ๋์์ต๋๋ค!');
router.navigate('/post/' + post.slug);
}
});
</script>
</div>
`;
}
renderLogin() {
return `
<div class="login-page">
<div class="login-container">
<h1>๋ก๊ทธ์ธ ๐</h1>
<form id="login-form">
<input type="text" id="username" placeholder="์ฌ์ฉ์๋ช
" required>
<input type="password" id="password" placeholder="๋น๋ฐ๋ฒํธ" required>
<button type="submit">๋ก๊ทธ์ธ</button>
</form>
<p><a href="/" data-link>โ ํ์ผ๋ก ๋์๊ฐ๊ธฐ</a></p>
</div>
<script>
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const success = await auth.login(username, password);
if (success) {
router.navigate('/');
} else {
alert('๋ก๊ทธ์ธ ์คํจ!');
}
});
</script>
</div>
`;
}
render404() {
return `
<div class="error-page">
${this.renderHeader()}
<div class="error-content">
<h1>404</h1>
<p>ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค ๐ข</p>
<a href="/" data-link>ํ์ผ๋ก ๋์๊ฐ๊ธฐ</a>
</div>
${this.renderFooter()}
</div>
`;
}
renderHeader() {
const isLoggedIn = this.auth.isAuthenticated();
return `
<header class="site-header">
<div class="container">
<a href="/" data-link class="logo">๋ด ๋ธ๋ก๊ทธ</a>
<nav>
<a href="/" data-link>ํ</a>
<a href="/posts" data-link>ํฌ์คํธ</a>
${isLoggedIn ? `
<a href="/write" data-link>๊ธ์ฐ๊ธฐ</a>
<button onclick="auth.logout(); router.navigate('/');">๋ก๊ทธ์์</button>
` : `
<a href="/login" data-link>๋ก๊ทธ์ธ</a>
`}
</nav>
</div>
</header>
`;
}
renderFooter() {
return `
<footer class="site-footer">
<div class="container">
<p>ยฉ 2024 ๋ด ๋ธ๋ก๊ทธ. Made with โค๏ธ and JavaScript</p>
<p>์ฌ๋ฅ๋ท์์ ๋ ๋ง์ ๊ฐ๋ฐ ํ์ ๋ง๋๋ณด์ธ์!</p>
</div>
</footer>
`;
}
// API ๋ฉ์๋๋ค
async fetchRecentPosts() {
// ์ค์ ๋ก๋ API ํธ์ถ
return [
{
slug: 'javascript-routing',
title: 'JavaScript ๋ผ์ฐํ
์๋ฒฝ ๊ฐ์ด๋',
excerpt: 'SPA ๋ผ์ฐํ
์ ๋ชจ๋ ๊ฒ',
coverImage: '/images/post1.jpg',
author: '๊ฐ๋ฐ์',
date: '2024-01-15'
}
// ... ๋ ๋ง์ ํฌ์คํธ
];
}
async fetchPosts({ page, category }) {
// API ํธ์ถ
return [];
}
async fetchPost(slug) {
// API ํธ์ถ
return null;
}
async savePost(post) {
// API ํธ์ถ
return true;
}
}
// ์ฑ ์์!
const blogSPA = new BlogSPA();
๐ ์ถํํด! ์์ ํ ๋ธ๋ก๊ทธ SPA๋ฅผ ๋ง๋ค์์ด!
์ด ํ๋ก์ ํธ์๋ ๋ค์ ๊ธฐ๋ฅ๋ค์ด ๋ชจ๋ ํฌํจ๋์ด ์์ด:
โ ๋ผ์ฐํ (History API)
โ ๋์ ๋ผ์ฐํธ ํ๋ผ๋ฏธํฐ
โ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ
โ ์ธ์ฆ ์์คํ
โ SEO ์ต์ ํ
โ ๋ค๋น๊ฒ์ด์ ๊ฐ๋
โ ๋ฐ์ํ ๋์์ธ
โ ํ์ด์ง๋ค์ด์
์ด ์ฝ๋๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์์ ๋ง์ ํ๋ก์ ํธ๋ฅผ ๋ง๋ค์ด๋ด! ๐ช
๐ ๋ค์ ๋จ๊ณ์ ํ์ต ๋ฆฌ์์ค
์ฌ๊ธฐ๊น์ง ์๋ค๋ฉด ์ ๋ง ๋๋จํด! ํ์ง๋ง ๋ฐฐ์์๋ ๋์ด ์์ง. ๋ ๊น์ด ๊ณต๋ถํ๊ณ ์ถ๋ค๋ฉด ์ด๋ฐ ๊ฒ๋ค์ ์ดํด๋ด:
๐ ํ๋ ์์ํฌ ํ์ต
โข React Router ์ฌํ
โข Vue Router ๋ง์คํฐ
โข Next.js (React SSR)
โข Nuxt.js (Vue SSR)
๐ฏ ๊ณ ๊ธ ์ฃผ์
โข ์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง
โข ์ ์ ์ฌ์ดํธ ์์ฑ (SSG)
โข ์ฆ๋ถ ์ ์ ์ฌ์์ฑ (ISR)
โข ๋ง์ดํฌ๋ก ํ๋ก ํธ์๋
โก ์ฑ๋ฅ ์ต์ ํ
โข ๋ฒ๋ค ์ต์ ํ
โข ์ด๋ฏธ์ง ์ต์ ํ
โข ์บ์ฑ ์ ๋ต
โข Web Vitals ๊ฐ์
๐ ์ถ์ฒ ํ์ต ๊ฒฝ๋ก
1๋จ๊ณ: ๊ธฐ์ด ๋ค์ง๊ธฐ
โข JavaScript ES6+ ๋ฌธ๋ฒ
โข DOM ์กฐ์
โข ์ด๋ฒคํธ ์ฒ๋ฆฌ
โข Promise์ async/await
2๋จ๊ณ: ๋ผ์ฐํ ์ดํดํ๊ธฐ
โข History API
โข URL ํ์ฑ
โข ์ ๊ทํํ์
โข ์ํ ๊ด๋ฆฌ
3๋จ๊ณ: ์ค์ ํ๋ก์ ํธ
โข ๊ฐ๋จํ SPA ๋ง๋ค๊ธฐ
โข ๋ผ์ฐํฐ ์ง์ ๊ตฌํ
โข ํ๋ ์์ํฌ ์ฌ์ฉ
โข ๋ฐฐํฌํ๊ธฐ
4๋จ๊ณ: ์ต์ ํ์ ๊ณ ๊ธ ๊ธฐ๋ฅ
โข SSR/SSG ๊ตฌํ
โข ์ฑ๋ฅ ์ต์ ํ
โข SEO ๊ฐ์
โข ํ ์คํ
๐ฌ ๋ง์น๋ฉฐ
์! ์ ๋ง ๊ธด ์ฌ์ ์ด์์ง? ๐ JavaScript ๋ผ์ฐํ ๊ณผ SPA ๋ค๋น๊ฒ์ด์ ์ ๋ํด ์ ๋ง ๋ง์ ๊ฑธ ๋ฐฐ์ ์ด. ์ฒ์์๋ ๋ณต์กํด ๋ณด์์ง๋ง, ํ๋์ฉ ๋ฏ์ด๋ณด๋๊น ๊ทธ๋ ๊ฒ ์ด๋ ต์ง ์์์ง?
ํต์ฌ์ ์ ๋ฆฌํ์๋ฉด:
๐ฏ ๊ธฐ์ตํด์ผ ํ ํต์ฌ ํฌ์ธํธ
1. SPA๋ ์ฌ์ฉ์ ๊ฒฝํ์ ํฌ๊ฒ ํฅ์์์ผ - ํ์ด์ง ์๋ก๊ณ ์นจ ์์ด ๋ถ๋๋ฌ์ด ์ ํ
2. ๋ผ์ฐํ ์ SPA์ ์ฌ์ฅ - URL ๊ด๋ฆฌ์ ๋ค๋น๊ฒ์ด์ ์ ํต์ฌ
3. ๋ ๊ฐ์ง ๋ฐฉ์์ด ์์ด - Hash ๊ธฐ๋ฐ๊ณผ History API ๊ธฐ๋ฐ
4. ๋ณด์๊ณผ ์ธ์ฆ์ ํ์ - ํด๋ผ์ด์ธํธ์ ์๋ฒ ๋ชจ๋์์ ์ฒดํฌ
5. ์ฑ๋ฅ ์ต์ ํ๊ฐ ์ค์ํด - ์ฝ๋ ์คํ๋ฆฌํ , ์บ์ฑ, ํ๋ฆฌํ์นญ
6. SEO๋ฅผ ์์ง ๋ง - ๋ฉํ ํ๊ทธ ๊ด๋ฆฌ์ SSR ๊ณ ๋ ค
7. ๋ชจ๋ฐ์ผ ์ต์ ํ๋ ํ์ - ํฐ์น ์ ์ค์ฒ์ ๋ฐ์ํ ๋์์ธ
8. ํ ์คํ ์ผ๋ก ์์ ์ฑ ํ๋ณด - ์ ๋ ํ ์คํธ์ E2E ํ ์คํธ
์ด์ ๋๋ ๋ฉ์ง SPA๋ฅผ ๋ง๋ค ์ ์์ด! ์ฒ์์๋ ์์ ํ๋ก์ ํธ๋ถํฐ ์์ํด์ ์ ์ ๋ณต์กํ ๊ธฐ๋ฅ์ ์ถ๊ฐํด๋๊ฐ๋ฉด ๋ผ. ์ค์ํ๋ ๊ฒ ๋๋ ต์ง ์์๋ ๋ผ. ์ค์๋ฅผ ํตํด ๋ฐฐ์ฐ๋ ๊ฒ ๊ฐ์ฅ ๋น ๋ฅธ ๋ฐฉ๋ฒ์ด๋๊น! ๐ช
๊ทธ๋ฆฌ๊ณ ํผ์ ๊ณ ๋ฏผํ์ง ๋ง๊ณ , ์ฌ๋ฅ๋ท ๊ฐ์ ์ปค๋ฎค๋ํฐ์์ ๋ค๋ฅธ ๊ฐ๋ฐ์๋ค๊ณผ ์ํตํ๋ฉด์ ๋ฐฐ์๋๊ฐ. ์ง๋ฌธํ๊ณ , ๋ต๋ณํ๊ณ , ์ง์์ ๋๋๋ค ๋ณด๋ฉด ์ด๋์ ์ ๋ฌธ๊ฐ๊ฐ ๋์ด ์์ ๊ฑฐ์ผ! ๐
์, ์ด์ ์ฝ๋ ์๋ํฐ๋ฅผ ์ด๊ณ ์ง์ ๋ง๋ค์ด๋ด! ์ฝ๊ธฐ๋ง ํ๋ ๊ฒ๋ณด๋ค ์ง์ ์ฝ๋ฉํ๋ ๊ฒ ๋ฐฑ ๋ฐฐ๋ ๋ ๋์์ด ๋ผ. ํ์ดํ ! ๐ฅ
๐ ์ฌ๊ธฐ๊น์ง ์ฝ์ด์ค์ ๊ณ ๋ง์!
์ด ๊ธ์ด ๋์์ด ๋๋ค๋ฉด ์ฃผ๋ณ ๊ฐ๋ฐ์ ์น๊ตฌ๋ค์๊ฒ๋ ๊ณต์ ํด์ค!
Happy Coding! ๐ปโจ
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.