我们在这个博客上谈了很多高级的Node.js和TypeScript概念,特别是领域驱动设计和大规模企业应用模式。然而,在收到读者的邮件后,我想看看TypeScript的基本入门项目是什么样子的,所以我把它放在一起。
前提条件
- 你应该安装了Node和npm
- 你应该熟悉Node和npm生态系统
- 你已经安装了一个代码编辑器(最好是VS Code,它是TypeScript的冠军)。
目标
在这个简短的指南中,我将指导你创建一个基本的TypeScript应用程序,并对其进行编译。实际上,这真的很容易!
之后,我们将设置一些脚本,用于在development ,为production ,并在production ,进行热加载。
关于TypeScript
TypeScript,由微软开发并贴上了 "可扩展的JavaScript "的标签,是JavaScript的超集,意味着JavaScript能做的一切,TypeScript都能做~(而且~做得更好)。
TypeScript的主要目的是解决两个问题。
- 为JavaScript开发者提供一个可选的类型系统。
- 为JavaScript开发者提供利用未来JavaScript版本的计划功能的能力,以对抗当前的JavaScript引擎。
我们在这个博客上的大部分主题都使用TypeScript,因为它更适合于创建持久的软件,而且让编译器帮助捕捉错误和验证类型是非常有帮助的。
初始设置
让我们创建一个文件夹,让我们在其中工作。
mkdir typescript-starter
cd typescript-starter
接下来,我们将设置项目package.json ,并添加依赖项。
设置 Node.js package.json
在创建package.json 时使用-y 标志将简单地批准所有的默认值。
npm init -y
将TypeScript添加为开发依赖项
这可能并不令人惊讶;)
npm install typescript --save-dev
在我们安装了typescript ,我们可以通过tsc 命令访问命令行TypeScript编译器。下面会有更多关于这个的内容。
为TypeScript安装周围的Node.js类型
TypeScript有Implicit, Explicit, 和Ambient类型。Ambient类型是被添加到全局执行范围中的类型。由于我们使用的是Node,如果我们能在Node的apis上获得类型安全和自动补全,那就更好了,比如file,path,process, 等等。这就是为Node安装DefinitelyTyped类型定义所要做的。
npm install @types/node --save-dev
创建一个tsconfig.json 。
tsconfig.json 是我们定义TypeScript编译器选项的地方。我们可以创建一个tsconfig,设置几个选项。
npx tsc --init --rootDir src --outDir build \
--esModuleInterop --resolveJsonModule --lib es6 \
--module commonjs --allowJs true --noImplicitAny true
rootDir:这是TypeScript寻找我们代码的地方。我们已经把它配置为在src/文件夹中寻找。这就是我们要写TypeScript的地方。outDir:TypeScript将我们编译的代码放在哪里。我们想让它进入build/文件夹。esModuleInterop:如果你在过去的几年里在JavaScript领域,你可能已经认识到模块系统已经有点失控了(AMD,SystemJS,ES Modules,等等)。对于一个需要更长时间讨论的话题,如果我们使用commonjs作为我们的模块系统(对于Node应用程序,你应该这样做),那么我们需要将此设置为true。resolveJsonModule:如果我们在这个项目中使用JSON,这个选项允许TypeScript使用它。lib:这个选项为我们的项目增加了环境类型,允许我们依靠不同Ecmascript版本的功能,测试库,甚至浏览器DOM api。我们想利用一些es6语言的特性。这一切都被编译成了es5。module:commonjs是2019年的标准Node模块系统。让我们使用这个。allowJs:如果你正在将一个旧的JavaScript项目转换为TypeScript,这个选项将允许你在.ts中包含.js的文件。noImplicitAny:在TypeScript文件中,不允许不明确地指定一个类型。每一个类型都需要有一个特定的类型或者明确的声明any。没有隐含的anys。
在这一点上,你应该有一个tsconfig.json ,看起来像这样。
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": ["es6"], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "build", /* Redirect output structure to the directory. */
"rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"resolveJsonModule": true /* Include modules imported with '.json' extension */
}
}
我们可以继续前进,清除那些我们不需要的注释内容。我们的tsconfig.json 应该是这样的。
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6"],
"allowJs": true,
"outDir": "build",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true
}
}
我们已经准备好运行我们的第一个TypeScript文件了。
创建src 文件夹并创建我们的第一个TypeScript文件
mkdir src
touch src/index.ts
让我们来写一些代码。
console.log('Hello world!')
编译我们的TypeScript
为了编译我们的代码,我们需要使用npx ,即Node包执行器来运行tsc 命令。tsc 将读取当前目录下的tsconfig.json ,并针对TypeScript编译器应用配置,以生成编译后的JavaScript代码。
npx tsc
我们编译后的代码
查看build/index.js ,我们已经编译了我们的第一个TypeScript文件。
"use strict";
console.log('Hello world!');
有用的配置和脚本
冷重载
冷重载对于本地开发是很好的。为了做到这一点,我们需要依靠另外几个包:ts-node ,用于直接运行TypeScript代码而不必等待它被编译,以及nodemon ,用于观察我们代码的变化,并在文件被改变时自动重启。
npm install --save-dev ts-node nodemon
添加一个nodemon.json 配置。
{
"watch": ["src"],
"ext": ".ts,.js",
"ignore": [],
"exec": "ts-node ./src/index.ts"
}
然后要运行这个项目,我们所要做的就是运行nodemon 。让我们为此添加一个脚本。
"start:dev": "nodemon",
通过运行npm run start:dev ,nodemon 将使用ts-node ./src/index.ts 来启动我们的应用程序,观察.ts 和.js 文件在/src 中的变化。
创建生产构建
为了清理和编译用于生产的项目,我们可以添加一个build 脚本。
安装rimraf ,这是一个跨平台的工具,其作用类似于rm -rf 命令(只是抹掉你告诉它的任何东西)。
npm install --save-dev rimraf
然后,把这个添加到你的package.json 。
"build": "rimraf ./build && tsc",
现在,当我们运行npm run build ,rimraf ,在TypeScript编译器向dist 发出新代码之前,将删除我们的旧build 文件夹。
生产启动脚本
为了在生产中启动应用程序,我们需要做的就是先运行build 命令,然后在build/index.js 执行编译后的JavaScript。
启动脚本看起来像这样。
"start": "npm run build && node build/index.js"
我告诉过你这很简单!现在,你可以走了。创造伟大的事物,我的朋友。
查看源代码
提醒一下,你可以在这里查看这个的全部源代码。
脚本概述
npm run start:dev
启动开发中的应用程序,使用nodemon 和ts-node 来进行冷重载。
npm run build
在build 构建应用程序,首先清理该文件夹。
npm run start
在生产中启动应用程序,首先用npm run build 构建项目,然后在build/index.js 执行编译后的JavaScript。