新手如何在Node.js中使用TypeScript
warning:
这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
安装Node.js和TypeScript:
确保你已经安装了Node.js。然后全局安装TypeScript:
npm install -g typescript初始化Node.js项目:
npm init -y安装TypeScript npm包:
npm install typescript --save-dev- 创建一个TypeScript文件,例如
index.ts。 编写TypeScript代码。例如:
function greet(name: string): string { return `Hello, ${name}!`; } console.log(greet('World'));编译TypeScript文件:
tsc index.ts这将生成一个
index.js文件,它是TypeScript编译为JavaScript的结果。运行JavaScript文件:
node index.js可选: 配置tsconfig.json。
运行
tsc --init生成一个tsconfig.json文件,你可以在其中配置编译选项。使用npm scripts来编译和运行TypeScript代码。
在
package.json中添加以下脚本:"scripts": { "build": "tsc", "start": "node .build/index.js" }现在可以使用
npm run build来编译代码,使用npm start来运行编译后的JavaScript代码。
评论已关闭