BÀI 1 - CÀI ĐẶT CƠ BẢN CHO MỘT SERVER
1. Cài đặt npm
Đảm bảo rằng Node và NPM đã được cài đặt trên máy tính của bạn. Bạn có thể tải xuống cả hai tại nodejs.org (NPM được bao gồm trong bản cài đặt Node của bạn)
2. Tạo một dự án React
Mở một thư mục và mở command hoặc terminal và nhập
yarn create vite app-name --template react # For yarn
npm create vite@latest app-name --template react # For npm
Tiếp tục chuyển đến vị trí của thư mục và cài đặt npm hoặc yarn
cd app-name
yarn # For yarn
npm install # For npm
Cấu trúc của thư mục sẽ tạm trông như thế này
app-name/
node_modules/
package.json
vite.config.js
yarn.lock or package-lock.json
.gitignore
src/
main.jsx
index.css
App.jsx
App.css
favicon.svg
logo.png
Vì chúng ta code server nên sửa nội tệp vite.config.js lại như này (bình thường mặc định nó sẽ khởi chạy từ index.html sau khi sửa nó sẽ chạy trong file main.jsx
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
build: {
manifest: true,
rollupOptions: {
input: "./src/main.jsx",
},
},
});
Tạo thư mục public và chuyển tệp index.html (và favicon.svg nếu có) và đó. Có thể làm nhanh như thế này
mkdir public
mv index.html public/
mv src/favicon.svg public/
Chỉnh sửa tệp index.html như sau
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module">
import RefreshRuntime from "http://localhost:3000/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>
<script type="module" src="http://localhost:3000/src/main.jsx"></script>
</body>
</html>
Trở lại thư mục mẹ, tạo tệp server.js và cài đặt express
touch server.js
yarn add express # For yarn
npm i express # For npm
Tệp server.js sẽ như sau
import express from "express"
import path, { dirname } from "path"
import { fileURLToPath } from "url"
const app = express()
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const PORT = process.env.PORT || 5000
app.use("/", express.static(path.join(__dirname, "public")))
app.get("/api/v1", (req, res) => {
res.json({
project: "React and Vite Express",
from: "Hama"
})
})
app.get("/*", (req, res) => {
res.sendFile(path.json(__dirname, "public", "index.html"))
})
app.listen(PORT, () => {
console.log("App running in port " + PORT)
})
Tuy nhiên các nội dung tĩnh như hình ảnh và video sẽ không hiển thị được. Để khắc phục mình thêm thư mục server và thêm tệp assets-router.js bên trong đó
mkdir server
touch server/assets-router.js
Nội dung tệp assets-router.js
import express from "express"
const router = express.Router()
const imageRegex = /\/.+\.(svg|png|jpg|png|jpeg)$/; // You can add other image formats
const videoRegex = /\/.+\.(mp4|ogv)$/
router.get(imageRegex, (req, res) => {
const filePath = req.path;
res.redirect(303, `http://localhost:3000/src${filePath}`);
});
router.get(videoRegex, (req, res) => {
const filePath = req.path;
res.redirect(303, `http://localhost:3000/src${filePath}`);
});
module.exports = router;
Và thêm nó và server.js
const assetsRouter = require("./server/assets-router")
app.use("/src", assetsRouter)
Cài đặt thêm Nodemon và Concurrently
yarn add --dev nodemon
or
npm i --save-dev nodemon
yarn add global concurrently
or
npm i -g concurrently
Sửa file package.json
"dev": "concurrently 'vite' 'nodemon server.js'"
Rồi xong, chạy và xem kết quả
yarn dev
or
npm run dev