Node.js使用TypeScript (一)

首先,創(chuàng)建一個(gè)新的項(xiàng)目目錄,并初始化 npm 項(xiàng)目:

mkdir my-nodejs-backend  
cd my-nodejs-backend  
npm init -y

我們需要安裝一些基本的依賴,包括 express(一個(gè)常用的 Node.js 框架)、typescript、ts-node(用于直接運(yùn)行 TypeScript 文件)、@types/express(Express 的類型定義)以及 @types/node(Node.js 的類型定義):

npm install express typescript ts-node @types/express @types/node --save

此外,為了更方便地管理開發(fā)依賴,我們可以安裝 nodemon 和 tsconfig-paths:

npm install nodemon tsconfig-paths --save-dev

在項(xiàng)目根目錄下創(chuàng)建一個(gè) tsconfig.json 文件,配置 TypeScript:

{  
  "compilerOptions": {  
    "target": "ES6",  
    "module": "commonjs",  
    "outDir": "./dist",  
    "rootDir": "./src",  
    "strict": true,  
    "esModuleInterop": true,  
    "skipLibCheck": true,  
    "forceConsistentCasingInFileNames": true,  
    "baseUrl": "./",  
    "paths": {  
      "*": ["src/*"]  
    }  
  },  
  "include": ["src/**/*"],  
  "exclude": ["node_modules"]  
}

src/app.ts

這個(gè)文件將包含 Express 應(yīng)用的配置:

import express from 'express';  
  
const app = express();  
const PORT = process.env.PORT || 3000;  
  
app.get('/', (req, res) => {  
  res.send('Hello, World!');  
});  
  
export default app;

src/index.ts

這個(gè)文件是應(yīng)用的入口點(diǎn):

import app from './app';  
  
const PORT = process.env.PORT || 3000;  
  
app.listen(PORT, () => {  
  console.log(`Server is running on port ${PORT}`);  
});

在項(xiàng)目根目錄下創(chuàng)建一個(gè) nodemon.json 文件,配置 nodemon:

{  
  "watch": ["src"],  
  "ext": "ts",  
  "exec": "ts-node ./src/index.ts"  
}

在 package.json 中添加一些方便的開發(fā)腳本:

"scripts": {  
  "start": "nodemon",  
  "build": "tsc",  
  "serve": "node dist/index.js"  
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容