BÀI 1 - CÀI ĐẶT CƠ BẢN CHO MỘT SERVER

1. Cài đặt npm

2. Tạo một dự án React

yarn create vite app-name --template react           # For yarn

npm create vite@latest app-name --template react  # For npm

cd app-name

yarn         # For yarn

npm install  # For npm

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

import { defineConfig } from "vite";

import react from "@vitejs/plugin-react";

export default defineConfig({

 plugins: [react()],

 build: {

   manifest: true,

   rollupOptions: {

     input: "./src/main.jsx",

   },

 },

});

mkdir public

mv index.html public/

mv src/favicon.svg public/

<!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>

touch server.js

yarn add express  # For yarn

npm i express     # For npm

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)

})

mkdir server

touch server/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;

const assetsRouter = require("./server/assets-router")

app.use("/src", assetsRouter)

yarn add --dev nodemon

 or

npm i --save-dev nodemon

yarn add global concurrently

 or

npm i -g concurrently

"dev": "concurrently 'vite' 'nodemon server.js'"

yarn dev

 or

npm run dev