[Node.js] 프로젝트 생성 with express 에서 프로젝트를 생성했다.
이번에는 정적 파일을 추가하고,
HTML 파일에 CSS,JS 파일을 적용시키는 방법을 기록하고자 한다.
📦{프로젝트 폴더명}
┣ 📜app.js
┣ 📜package-lock.json
┗ 📜package.json
프로젝트 루트 경로에
public 폴더를 생성한다.
public 폴더에 html 폴더를 생성하고
index.html 파일을 생성한다.
<!-- public/html/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
</body>
</html>
public 폴더에 css 폴더를 생성하고
index.css 파일을 생성한다.
/* public/css/index.css */ /* 우선 내용은 생략 */4. js 파일 생성
public 폴더에 js 폴더를 생성하고
index.js파일을 생성한다.// public/js/index.js // 우선 내용은 생략5. app.js 내용 수정
// app.js const express = require('express'); const path = require('path'); const app = express(); const port = 3000; app.set('port', process.env.PORT || 3000); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', (req, res) => { res.sendFile(__dirname + '/public/html/index.html'); }); app.listen(app.get('port'), () => { console.log(app.get('port'), '번 포트에서 대기 중'); });
app.use에 기입된 폴더의 정적 파일들을
express에서 제공가능한 상태가 되었다.6. index.html 내용 수정
<!-- public/html/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <!-- 외부 css 파일 적용 --> <link rel="stylesheet" href="/css/index.css" /> </head> <body> <!-- 외부 js 파일 적용 --> <script src="/js/index.js"></script> </body> </html>
head 태그에 외부 css 파일 적용을 위한 경로를 적는다.
body 태그 마지막 부분에 외부 js 파일 적용을 위한 경로를 적는다.7. 서버 실행
$ npm start3,4,6번 과정에서 내용을 생략했기에,
서버를 실행해도 적용이 된 줄 모를 것이다.
html, css, js 파일에 내용을 추가하여
적용이 잘 되는지 확인해보는 것을 추천한다.프로젝트 구조
📦{프로젝트 폴더명} ┣ 📂public ┃ ┣ 📂css ┃ ┃ ┗ 📜index.css ┃ ┣ 📂html ┃ ┃ ┣ 📜index.html ┃ ┗ 📂js ┃ ┃ ┗ 📜index.js ┣ 📜app.js ┣ 📜package-lock.json ┗ 📜package.json
node_modules폴더는 생략했다.