1.首先新建一個項目
npm init -yes
2.開啟Typescript依賴
npm install typescript --save-dev
安裝typescript,現在我們可以通過命令行來使用tsc
命令
3.安裝nodejs類型
npm install @types/node --save-dev
4.使用命令創建一個tsconfig.json文件
npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
去除了無用的注釋它的內容像這樣的
{
"compilerOptions": {
"target": "es5",
"lib": ["es6"],
"module": "commonjs",
"rootDir": "src",
"resolveJsonModule": true,
"allowJs": true,
"outDir": "build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"skipLibCheck": true
}
}
rootDir
: typescript尋找我們編寫代碼的地方,現在配置為src目錄,現在需要在項目錄中創建一個src
文件夾編寫ts代碼
5.編寫ts代碼
新建src/index.ts
文件
console.log("hello 梁典典")
執行編譯命令npx tsc
,在項目目錄中會自動創建build/index.js
文件,內容如下
"use strict";
console.log("hello 梁典典");
6.配置熱重載功能
它將監聽你的代碼自動進行惹更新
npm install --save-dev ts-node nodemon
項目根目錄創建nodemon.json
文件
{
"watch": ["src"],
"ext": ".ts,.js",
"ignore": [],
"exec": "ts-node ./src/index.ts"
}
在package,json
新增一個腳本命令
"start:dev": "nodemon"
在命令行執行npm run start:dev
,就可以自動監聽文件更改了
7.創建支持清理和編譯的生成版本
安裝rimraf
npm install --save-dev rimraf
添加腳本
"build": "rimraf ./build && tsc",
8. 創建生產啟動腳本
"start": "npm run build && node build/index.js"
現在可以使用typescript編寫代碼了