使用typescript开发nodejs

Yi node.js 2023-07-05 299

1、nodejs 环境

node:v16.20.0 npm:9.6.7

2、typescript 环境

@types/node typescript ts-node 安装脚本

npm install -D typescript ts-node @types/node

3、项目结构

hello
├─package.json  // nodejs配置文件
├─tsconfig.json // ts配置文件
├─main.ts // 运行ts入口
├─main.js // 运行js入口
├─src // 源代码
│ └─say-hello.ts
├─build //生成的代码
│ ├─say-hello.js
│ └─say-hello.d.ts

package.json

{
  "name": "hello",
  "version": "1.0.0",
  "description": "测试项目",
  "main": "main.js",
  "scripts": {
    "build": "echo 直接打包 && tsc",
    "dev": "echo 打包同时监听ts文件变动自动打包 && tsc --watch",
    "start": "echo 生成JS并启动JS && tsc && node ./main.js",
    "start:ts": "echo 直接启动TS && ts-node ./main.ts"
  },
  "keywords": [ ], 
  "author": "Yi",
  "license": "ISC",
  "dependencies": { },
  "devDependencies": {
    "@types/node": "^20.3.0",
    "ts-node": "^10.9.1",
    "typescript": "^4.5.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",   //指定生成哪个模块系统代码
    "target": "es6",        //目标代码类型
    "noImplicitAny": false, //在表达式和声明上有隐含的'any'类型时报错。
    "sourceMap": false,      //生成 js 与 ts 的映射,方便直接使用 ts 文件进行调试
    "rootDir":"./src",      //仅用来控制输出的目录结构--outDir。
    "outDir":"./build",     //重定向输出目录。
    "declaration": true,     // 编译过程中,是否生成 TypeScript 的声明文件,如 *.d.ts
    "watch":false            //在监视模式下运行编译器。会监视输出文件,在它们改变时重新编译。
  },
  "include":[
    "./src/**/*"
  ],
  "exclude":[ ]
}

say-hello.ts

/**
 * 打招呼
 * @param name 内容
 */
const sayHello = (name: string) => {
    console.log('Hello ' + name);
}

// 导出方法
export {
  sayHello
}

main.ts

// 加载模块
import {sayHello} from "./src/say-hello";
// 使用模块
sayHello("world")

main.js

// 加载模块
const say_hello = require("./build/say-hello")
// 继续导出模块
exports.sayHello=say_hello.sayHello
// 使用模块
exports.sayHello("world")