- 在欲放置專案資料夾的路徑,建立專案資料夾。
mkdir html5-js-api-base
- 切換工作目錄到專案資料夾內。
cd html5-js-api-base
- 使用 npm 初始化專案。
npm init -y
- 利用 npm 安裝所需套件。
npm i express
npm i serve-index
npm i --save-dev nodemon
- 編輯 package.json,使用 ESM。
"type": "module",
- 在專案目錄建立 public 資料夾,並放入一支 html 檔。
mkdir public
- 在專案目錄新增檔案 index.js,並輸入以下內容。
import express from "express";
import serveIndex from "serve-index";
const web_port = 3031;
const app = express();
app.use(express.static("public"));
app.use("/", serveIndex("public", { icons: true }));
app.listen(web_port, () => {
console.log(`伺服器啟動於通訊埠:${web_port}`);
});
- 修改 package.json,加入啟動的 scripts。
"scripts": {
"dev": "nodemon index.js"
}
- 在專案目錄的命令列,輸入下式啟動伺服器,並於瀏覽器上查看
http://localhost:3031
。
npm run dev