前言
试想一下这么一个情况,你想要对一些数据或文件进行批量处理,但是你用的编程语言比较顺手的或者工作使用的编程语言是Typescript或者Javascript,因此想要使用Typescript来实现这些操作。
当然,要想完成这个工作,哪怕你使用python,shell也是可以完成的,但是这里只谈论使用Typescript.
现在就是这个情况,我想要写一个nodejs的TS项目,能够编译我写的代码,并且执行代码,得到我想要的结果。
一、明确需求
既然知道了目标,那么就要先明确一下需求。
现在就是这个情况,我想要写一个nodejs的TS项目,能够编译我写的代码,并且执行代码,得到我想要的结果。
从这里可得到以下信息:
- 项目是使用nodejs,编程语言是Typescript
- 要能编译ts代码
- 最后执行ts代码,得到想要的输出结果。
粗略设计
- 首先定义一个build输出目录,遵从一般的项目标准,使用
./dist
- 定义一个入口文件,ts编译后是js,那么入口文件就是
./dist/index.js
- 使用命令来执行操作,一个
build
用来编译代码,一个dev
来编译和执行。 - 源码的入口文件是
src/index.ts
二、创建项目
使用你的包管理工具(我使用的是pnpm
,如果你使用的是npm
、yarn
或者其他包管理工具,则执行相同的操作即可),初始化一个项目
1. 新建文件夹
mkdir my_project
cd my_project
2. 初始化项目
pnpm init
然后就是输入各种项目信息,创建完毕后当前目录会多出一个package.json
文件,内容如下
{
"name": "my_project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
3. 安装依赖
这里主要是安装typescript的编译依赖和支持nodejs库的一些依赖。
pnpm install typescript @types/node
然后使用npx来初始化一下typescript的配置文件
npx tsc --init
此时当前目录下会多出一个tsconfig.json
,这个是全局的ts配置文件,内容如下
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type met