使用babel配置typescript开发环境
一、项目构建1、创建文件夹并且初始化npm init -y2、安装babel依赖包yarn add @babel/cli @babel/core @babel/preset-env@babel/preset-typescript typescript -D3、在项目下创建一个babel.config.js文件module.exports = {presets: [['@babel/preset-e
·
一、项目构建
-
1、创建文件夹并且初始化
npm init -y
-
2、安装
babel依赖包yarn add @babel/cli @babel/core @babel/preset-env @babel/preset-typescript typescript -D -
3、在项目下创建一个
babel.config.js文件module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], '@babel/preset-typescript', ], }; -
4、初始化
ts的配置文件,关于配置文件的内容就不介绍,有兴趣的可以参考tsc --init{ "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": [ "src" ] } -
5、在
package.json中配置编译命令"scripts": { "babel": "babel src --out-dir dist --extensions \".ts\"" }, -
6、开心的写
typescript代码
二、使用typescript搭建express项目
-
1、初始化项目
npm init -y tsc --init -
2、修改
tsconfig.json文件内容{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "baseUrl": "src" }, "exclude": ["node_modules"], "include": ["./src/**/*.ts"] } -
3、安装
express的依赖包yarn add express yarn add @types/express -
4、在
src/index.ts文件中书写代码import express, { Express, Request, Response, NextFunction } from 'express'; const PORT: number = 3000; const app: Express = express(); app.get('/', async (req: Request, res: Response, next: NextFunction) => { res.json({ code: 0, message: 'success', }); }); app.listen(PORT, () => { console.log(`服务已经启动:localhost:${PORT}`); }); -
5、在
package.json中配置启动命令"scripts": { "build": "tsc", "start": "ts-node-dev --respawn src/index.ts", "dev": "nodemon --exec ts-node --files src/index.ts" },开发环境启动命令可以是用
dev或者start,如果你要使用start启动方式就要多安装两个依赖包yarn add ts-node-dev typescript -D
更多推荐




所有评论(0)