Node.js和Express中設置TypeScript的實現(xiàn)步驟
在這篇文章中,我們將介紹在Express應用程序中設置TypeScript的最佳方法,了解與之相關的基本限制。
創(chuàng)建初始文件夾和package.json
mkdir node-express-typescript cd node-express-typescript npm init --yes
在初始化package.json文件之后,新創(chuàng)建的文件可能會像下面的代碼一樣:
{
"name": "Your File Name",
"version": "1.0.0",
"description": "",
"main": "index.ts", // 將入口點從js更改為.ts
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC"
}
安裝TypeScript和其他依賴項
npm install express mongoose cors mongodb dotenv
npm install -D typescript ts-node-dev @types/express @types/cors
生成tsconfig.json文件
npx tsc --init
上述命令將生成一個名為tsconfig.json的新文件,其中包含以下默認的編譯器選項:
target: es2016 module: commonjs strict: true esModuleInterop: true skipLibCheck: true forceConsistentCasingInFileNames: true
在打開tsconfig.json文件后,您會看到許多其他被注釋掉的編譯器選項。在tsconfig.json中,compilerOptions是一個必填字段,需要指定。
- 將rootDir和outDir設置為src和dist文件夾
{
"compilerOptions": {
"outDir": "./dist"
// other options remain same
}
}
使用.ts擴展名創(chuàng)建一個Express服務器
創(chuàng)建一個名為index.ts的文件并打開它
import express, { Express, Request, Response , Application } from 'express';
import dotenv from 'dotenv';
//For env File
dotenv.config();
const app: Application = express();
const port = process.env.PORT || 8000;
app.get('/', (req: Request, res: Response) => {
res.send('Welcome to Express & TypeScript Server');
});
app.listen(port, () => {
console.log(`Server is Fire at http://localhost:${port}`);
});
監(jiān)聽文件更改并構建目錄
npm install nodemon
安裝這些開發(fā)依賴項后,更新package.json文件中的腳本:
{
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "nodemon index.ts"
}
}
運行代碼
npm run dev
如果一切正常,您將在控制臺中看到以下消息:
Server is Fire at http://localhost:8000

到此這篇關于Node.js和Express中設置TypeScript的實現(xiàn)步驟的文章就介紹到這了,更多相關Node和Express設置TypeScript內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Node.js操作MySQL8.0數(shù)據(jù)庫無法連接的問題解決
使用node.js連接數(shù)據(jù)庫MySQL 8時候,顯示報錯 ER_NOT_SUPPORTED_AUTH_MODE,本文就來介紹一下解決方法,感興趣的可以了解一下2023-10-10
切換到淘寶最新npm鏡像源的全面指南(支持 Windows、macOS 和多種 Linux
在開發(fā)過程中,npm 是前端開發(fā)者不可或缺的工具,但對于國內(nèi)的開發(fā)者來說,npm 官方源在下載速度上存在一定的瓶頸,本文將詳細介紹如何在 Windows、macOS 以及各類 Linux 發(fā)行版上切換到淘寶的 npm 鏡像源,需要的朋友可以參考下2025-03-03

