一、安装
npm install typescript
二、初始化
1. 初始化命令
tsc --init
2. 编辑配置文件
// tsconfig.json
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"allowJs": true, /* Allow javascript files to be compiled. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */
/* Module Resolution Options */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"include": [
"src/*",
"src/**/*"
],
"exclude": [
"node_modules"
]
}
// package.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"tsc:w": "tsc -w"
},
...
三、运行
(一)先编译再运行
// 1. 编译“./src”下的*.ts文件
tsc
// 2. 运行生成的“./dist”下的*.js文件
node app.js
(二)免编译运行
// 1. 安装ts-node
npm install ts-node -g
// 2. 直接运行*.ts文件(类似node 运行*.js文件)
ts-node app.ts