Node.js和Express中設(shè)置TypeScript的實現(xiàn)步驟
在這篇文章中,我們將介紹在Express應(yīng)用程序中設(shè)置TypeScript的最佳方法,了解與之相關(guān)的基本限制。
創(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的新文件,其中包含以下默認(rèn)的編譯器選項:
target: es2016 module: commonjs strict: true esModuleInterop: true skipLibCheck: true forceConsistentCasingInFileNames: true
在打開tsconfig.json文件后,您會看到許多其他被注釋掉的編譯器選項。在tsconfig.json中,compilerOptions是一個必填字段,需要指定。
- 將rootDir和outDir設(shè)置為src和dist文件夾
{
"compilerOptions": {
"outDir": "./dist"
// other options remain same
}
}
使用.ts擴(kuò)展名創(chuàng)建一個Express服務(wù)器
創(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)聽文件更改并構(gòu)建目錄
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

到此這篇關(guān)于Node.js和Express中設(shè)置TypeScript的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)Node和Express設(shè)置TypeScript內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React+react-dropzone+node.js實現(xiàn)圖片上傳的示例代碼
本篇文章主要介紹了React+react-dropzone+node.js實現(xiàn)圖片上傳的示例代碼,非常具有實用價值,需要的朋友可以參考下2017-08-08
ajax+node+request爬取網(wǎng)絡(luò)圖片的實例(宅男福利)
下面小編就為大家?guī)硪黄猘jax+node+request爬取網(wǎng)絡(luò)圖片的實例(宅男福利)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
node實現(xiàn)批量上傳本地圖片轉(zhuǎn)為圖片CDN的項目實踐
本文主要介紹了node實現(xiàn)批量上傳本地圖片轉(zhuǎn)為圖片CDN的項目實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
windows系統(tǒng)下安裝yarn的詳細(xì)教程
yarn是一個新的JS包管理工具,它的出現(xiàn)是為了彌補npm的一些缺陷,下面這篇文章主要給大家介紹了關(guān)于windows系統(tǒng)下安裝yarn的詳細(xì)教程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
使用travis-ci如何持續(xù)部署node.js應(yīng)用詳解
最近在學(xué)習(xí)使用 travis-ci 對項目進(jìn)行持續(xù)集成測試,所以下面這篇文章主要給大家介紹了關(guān)于使用travis-ci如何持續(xù)部署node.js應(yīng)用的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07

