- 安装依赖
λ yarn add typescript types/node concurrently nodemon wait-on -D
- 初始化一个 tsconfig.json
λ ./node_modules/.bin/tsc --init
- 编写 tsconfig.json
{
"compilerOptions": {
"target": "es6" /* 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'. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
"baseUrl": "./",
"removeComments": true /* 不要向输出发出注释。 */,
"strict": true /* Enable all strict type-checking options. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"experimentalDecorators": true /* 为ES7装饰器提供实验支持。 */,
"emitDecoratorMetadata": true /* 装饰器支持. */
},
"exclude": ["node_modules"]
}
- 创建 tsconfig.build.json
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist"]
}
- 创建 nodemon.json
{
"watch": ["dist"],
"ext": "js",
"exec": "node dist/index"
}
- package.json
{
"scripts": {
"start": "concurrently --handle-input "wait-on ./dist/index.js && nodemon" "tsc -w -p tsconfig.build.json" "
},
"devDependencies": {
"@types/node": "^12.0.7",
"typescript": "^3.5.1",
"wait-on": "^3.2.0",
"concurrently": "^4.1.0",
"nodemon": "^1.19.1"
}
}
执行命令
λ npm start
添加测试 更多 github
- 安装jest的vscode插件也行
- 安装依赖
λ npm i -D @types/jest jest ts-jest ts-node
- 增加scripts
"scripts": {
...
"test": "jest",
"coverage": "jest --coverage"
}
- 设置VScode的launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": [
"${relativeFile}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"outFiles": [
"${workspaceFolder}/**/*.js"
],
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
]
}
- 设置配置文件jest.config.js
module.exports = {
transform: { "^.+\.ts?$": "ts-jest" },
testEnvironment: "node",
testRegex: "/test/.*\.(test|spec)?\.(ts|tsx)$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
};
- 添加测试脚本
/test/test.test.ts
it("tobe", () => {
expect("asd").toBe("asd");
});
- 运行测试
npm t
关于 ts-node
可以单独的运行ts文件,而无需编译
λ npm i -g ts-node
λ ts-node index.ts
hello ts