首页 > 编程语言 >从零开始创建一个nodejs+ts+express+热加载的简易项目

从零开始创建一个nodejs+ts+express+热加载的简易项目

时间:2024-05-30 13:43:57浏览次数:21  
标签:node src TypeScript nodejs app express ts

为了搭建一个 nodejs + express + ts + 热加载 的一个简易项目,需要配置一些基础的文件来确保 ts 代码能被编译和正确的运行。下面是一个详细的配置例子,以供参考。

1. 安装 Node.js:

确保系统上已经安装了 Node.js。这一步省略,安装也很简单。

2. 初始化项目

创建一个新的项目目录并进入这个目录,然后使用 yarn 初始化一个新项目。

mkdir demo
cd demo
yarn init -y	#使用默认设置快速初始化

3. 安装依赖

安装 ExpressTypeScript 作为项目依赖,并安装 @types/express@types/node 作为开发依赖,这些类型定义将帮助你在 TypeScript 代码中获取自动补全和类型检查:

yarn add express typescript --save
yarn add @types/express @types/node --dev

4. 配置 TypeScript

创建一个名为 tsconfig.json 的文件,这个文件是 TypeScript 编译器的配置文件。可以使用 tsc --init 命令快速生成一个默认的配置文件, 并根据需要进行修改:

npx tsc --init

这会生成一个包含默认设置的 tsconfig.json 文件。你可以根据需要修改这些设置。

{
  "compilerOptions": {
    /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "target": "es6",
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,  /* Disallow inconsistently cased references to the same file. */
    "outDir": "./dist",                       /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "resolveJsonModule": true,                /* Includes all files under node_modules or @types when resolving modules. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  },  
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

在这个配置中,我们指定了输出目录为 dist ,源代码目录为 src ,并启用了严格类型检查。

5. 创建源代码目录和文件

在src目录下创建你的TypeScript文件。例如,你可以创建一个 app.ts 文件作为你的 Express 应用的入口点,并在其中编写你的 Express 路由和中间件。

mkdir src
touch src/app.ts

app.ts 中,你可以这样编写一个简单的 Express 应用:

// src/app.ts

import express from 'express';

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello, TypeScript and Express!');
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

6. 编译和运行应用

在你的 package.json 中添加一个脚本来编译和运行你的应用:

{
  "name": "demo",
  "version": "1.0.0",
  "main": "dist/app.js",
  "scripts": {
    "build": "tsc",
    "start": "node dist/app.js"
  },
  "dependencies": {
    "express": "^4.19.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.21",
    "@types/node": "^20.12.13",
    "typescript": "^5.4.5"
  }
}

7. 编译TypeScript代码

在命令行中运行 npm run build 命令来编译你的 TypeScript 代码。这将会根据 tsconfig.json 配置文件中的设置,将 src 目录下的 .ts 文件编译成 JavaScript 文件,并输出到 dist 目录。

npm run build

8. 运行编译后的应用

一旦 TypeScript 代码被编译成 JavaScript,你就可以使用 Node.js 来运行这个应用。在命令行中运行 npm start 命令来启动你的 Express 应用。

npm start

你应该会看到类似以下的输出,表示你的服务器正在运行:

Server is running on port 3000.

9. 验证应用

现在,你可以打开浏览器并访问 http://localhost:3000/ 来查看你的 Express 应用是否按预期工作。你应该能看到 "Hello, TypeScript and Express!" 这样的消息。

10. 设置开发服务器(可选)

为了在开发过程中自动重新编译并运行你的代码(即热加载),你可以使用 nodemon 这样的工具。首先,你需要安装 nodemon 作为开发依赖:

npm install --save-dev nodemon

然后,在 package.json 中更新你的 scripts 部分,添加一个 dev 脚本来使用 nodemon 启动你的应用:

"scripts": {
  "build": "tsc",
  "start": "node dist/app.js",
  "dev": "nodemon --exec \"npx ts-node\" src/app.ts"
},

现在,你可以使用 npm run dev 命令来启动你的开发服务器。这将会使用 ts-node 来直接运行你的 TypeScript 代码,并且当文件发生更改时,nodemon 会自动重启你的应用。

注意:在上面的 dev 脚本中,我们使用了 ts-node 而不是编译后的 JavaScript 代码。这是为了在开发过程中提供更快的反馈循环,但请注意在生产环境中你应该始终使用编译后的 JavaScript 代码。

11. 其他配置和扩展(可选)

根据你的项目需求,你可能还需要配置其他工具或库,如 Webpack 进行更复杂的构建和打包,ESLint 进行代码质量检查,Prettier 进行代码格式化等。这些配置和扩展可以根据你的具体需求进行添加和调整。

标签:node,src,TypeScript,nodejs,app,express,ts
From: https://www.cnblogs.com/operate/p/18222070

相关文章

  • TypeScript error TS2345 All In One
    TypeScripterrorTS2345AllInOneerrorTS2345:Argumentoftype'number'isnotassignabletoparameteroftype'string'.errorsfunctiondailyTemperatures(temperatures:number[]):number[]{//❌errorTS2345:Argumentoftype......
  • amCharts绘制堆叠面积图
    代码案例<!DOCTYPEhtml><html><head><scriptsrc="https://cdn.amcharts.com/lib/5/index.js"></script><scriptsrc="https://cdn.amcharts.com/lib/5/xy.js"></script><scriptsrc=&qu......
  • amCharts绘制折线图比较
    代码案例<!DOCTYPEhtml><html><head><scriptsrc="https://cdn.amcharts.com/lib/5/index.js"></script><scriptsrc="https://cdn.amcharts.com/lib/5/xy.js"></script><scriptsrc=&qu......
  • 使用 Bootstrap 5 无法在 php 文件中实现智能识别
    我使用VisualStudioCode在php文件中使用Bootstrap5。Bootstrap会在我编写HTML代码时向我显示建议,如第一张图片。但当我编写HTML代码时,它什么也不显示,如第二张图片。我尝试使用了许多扩展,并在设置中将php的执行路径和"php":"html"设置为emmet语言。我......
  • Highcharts绘制饼图
    代码案例<html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1"> <title>HighchartsExa......
  • bootstrapping
    在这段RMarkdown代码中,代表bootstrapping思想的代码片段是以下几段:这部分代码使用bootstrapping方法来估计活性(Active)和抑制(Repressed)状态下ave列的中位数:active_med<-c()repress_med<-c()for(repin1:100){active_sample<-sample(active_rep$ave,size=leng......
  • css21 CSS Fonts
    https://www.w3schools.com/css/css_font.asp Choosingtherightfontforyourwebsiteisimportant!FontSelectionisImportantChoosingtherightfonthasahugeimpactonhowthereadersexperienceawebsite.Therightfontcancreateastrongidentity......
  • 基于node+express的文学交流平台的设计与实论文
    摘要本文学交流网站拥有丰富的文学作品资源,涵盖小说、散文、诗歌、戏剧等各类文学作品,用户可以在平台上轻松浏览、阅读、分享和评论作品,满足对文学作品的热爱与追求。除了作品展示,文学交流平台网站还注重用户之间的互动与交流。它设有社区交流功能,用户可以在平台上发表......
  • 联邦学习DLG攻击_NeurIPS2019_Deep Leakage from Gradients_深度梯度泄露,模型逆向攻击
    联邦学习联邦学习DLG攻击_NeurIPS2019_DeepLeakagefromGradients_深度梯度泄露发现了梯度可以倒推参数的问题文章目录要开始看些安全的内容了!一、Abstract二、Introduction2.1联邦学习的背景:2.2提出疑问:「梯度共用」计划有否保障每名参加者的训练资料集的私隐?2.......
  • 【jetson nano】烧录系统
    烧录固件 烧录固件是为了让板子用tf卡作为系统启动(非板载启动),一般来说只需要刷写一遍。安装vm,找到虚拟机镜像,解压part01就能获取镜像。 打开vm,打开此虚拟机镜像,账号clb,密码为123456短接23脚进入烧录模式,使用Micro-USB连接线连接Nano和电脑,然后DC电源上电。可以看到电源......