Parcel은 간편하게 웹 애플리케이션을 번들링하는 도구로서, 서버와 클라이언트 코드를 효율적으로 분리할 수 있습니다. 다음은 이를 위한 방법입니다.
1. 폴더 구조 설계하기
먼저, 서버와 클라이언트 코드를 분리하기 위해 폴더 구조를 설계합니다. 일반적인 구조로는 다음과 같이 할 수 있습니다.
project
├─ server
│ ├─ src
│ │ └─ index.js
│ └─ package.json
└─ client
├─ src
│ ├─ index.html
│ └─ index.js
└─ package.json
여기서 server
폴더에는 서버 코드가 위치하고, client
폴더에는 클라이언트 코드가 위치합니다.
2. 서버 코드 작성하기
server
폴더 내에 src
폴더를 생성하고, index.js
파일을 작성합니다.
// server/src/index.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello from server!');
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
3. 클라이언트 코드 작성하기
client
폴더 내에 src
폴더를 생성하고, index.html
과 index.js
파일을 작성합니다.
<!-- client/src/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Client</title>
</head>
<body>
<h1>Hello from client!</h1>
<script src="index.js"></script>
</body>
</html>
// client/src/index.js
console.log('Hello from client!');
4. Parcel 설정하기
각각의 코드를 작성한 후, server
와 client
폴더 내에서 package.json
파일을 생성합니다. 각각의 package.json
파일에는 다음과 같이 start
스크립트를 추가합니다.
// server/package.json
{
"name": "server",
"scripts": {
"start": "node src/index.js"
}
}
// client/package.json
{
"name": "client",
"scripts": {
"start": "parcel src/index.html"
}
}
5. 실행하기
터미널에서 server
와 client
폴더 각각에서 npm start
명령어를 실행합니다. 이제 각각의 코드가 서버와 클라이언트로 실행되며, 서버는 포트 3000에서 리스닝하게 됩니다. 브라우저에서 http://localhost:3000
에 접속하면 서버에서 “Hello from server!”를, 개발자 콘솔에서는 “Hello from client!”를 확인할 수 있습니다.
이처럼 Parcel을 사용하여 서버와 클라이언트 코드를 효율적으로 분리할 수 있으며, 가독성과 유지 보수성을 높일 수 있습니다. Parcel을 통해 간단한 웹 애플리케이션을 개발하고자 한다면, 이 방법을 적용해 보세요!
참고 문서:
- Parcel 공식 문서: https://parceljs.org/
- Express 공식 문서: https://expressjs.com/