美文网首页
Koa 2+TypeScript简单配置

Koa 2+TypeScript简单配置

作者: Collie | 来源:发表于2019-08-27 14:14 被阅读0次

    Step 1

    npm init //初始化项目时最好将提示的字段都填上,否则在下面的npm install时有警告
    // 安装依赖
    npm i --save koa koa-router tslib
    npm i --save-dev typescript nodemon
    npm i --save-dev @types/koa @types/koa-router
    

    tslib依赖用于在tsconfig.json的target选项设置为es2017以下时添加async/await等支持https://github.com/Microsoft/tslib

    01.PNG 02.PNG

    Step 2

    添加tsconfig.json配置,为了使用原生的Async/Await,可以将编译的目标版本target设置为"es2017"
    进一步地,可参考https://www.jianshu.com/p/912747f07025

    {
        "compilerOptions": {
            "allowJs": true,
            // 允许编译javascript文件
            "allowUnreachableCode": true,
            // 不报告执行不到的代码错误。
            "allowUnusedLabels": false,
            // 不报告未使用的标签错误
            "alwaysStrict": true,
            // 以严格模式解析并为每个源文件生成"use strict"语句
            "baseUrl": ".",
            // 解析非相对模块名的基准目录
            "checkJs": true,
            // 在javascript文件中报告错误
            // 只有当"allowJs"置为true时才能指定
            // "composite": true,
            // Ensure TypeScript can determine
            // where to find the outputs of the referenced project to compile project.
            "declaration": true,
            // 生成相应的.d.ts文件
            // 不能与isolatedModules同时指定
            "declarationDir": "build/declaration",
            // 生成声明文件的输出路径
            // 只有当"declaration"置为true时才能指定
            // 且不能与outFile同时指定
            "disableSizeLimit": true,
            // 禁用JavaScript工程体积大小的限制
            "downlevelIteration": true,
            // Provide full support for
            // iterables in for..of, spread and destructuring
            // when targeting ES5 or ES3
            "diagnostics": true,
            // 显示诊断信息
            "emitDecoratorMetadata": true,
            // 给源码里的装饰器声明加上设计类型元数据。
            // Emit design-type metadata for decorated declarations in source.
            "experimentalDecorators": true,
            // 启用实验性的ES装饰器
            "extendedDiagnostics": true,
            // Show verbose diagnostic information
            "forceConsistentCasingInFileNames": true,
            // 禁止对同一个文件的不一致的引用
            "importHelpers": false,
            // 从 tslib 导入辅助工具函数(如 __extends, __rest等)
            // Import emit helpers (e.g. '__extends', '__rest', etc..) from tslib.
            // Requires TypeScript version 2.1 or later.
            // 默认为false
            "incremental": true,
            // 启用增量编译
            // default: true if composite is on, false otherwise
            // Enable incremental compilation by
            // reading/writing information from prior compilations to a file on disk.
            // This file is controlled by the --tsBuildInfoFile flag.
            "inlineSourceMap": true,
            // 生成单个sourcemaps文件,而不是将每sourcemaps生成不同的文件。
            "inlineSources": true,
            // 将代码与sourcemaps生成到一个文件中,
            // 要求同时设置了 --inlineSourceMap或 --sourceMap属性。
            "isolatedModules": true,
            // 将每个文件作为单独的模块进行转译(Transpile)
            // (与“ts.transpileModule”类似)
            // 不可与outFile或declaration同时指定
            "jsx": "react",
            // 在.tsx文件里支持JSX
            "lib": [
                "dom",
                "es2015",
                "es2016",
                "es2017",
                "es2018"
            ],
            // 编译过程中需要引入的库文件的列表。
            // Specify library file to be included in the compilation.
            // Requires TypeScript version 2.0 or later.
            "listEmittedFiles": false,
            // 打印出编译后生成文件的名字
            "listFiles": false,
            // 编译过程中打印文件名
            "module": "CommonJS",
            // 指定生成哪个模块系统代码:
            // "None", "CommonJS", "AMD",
            // "System", "UMD", "ES6"或 "ES2015"
            // 只有 "AMD"和 "System"能和 --outFile一起使用。
            // "ES6"和 "ES2015"可使用在目标输出为 "ES5"或更低的情况下
            // 默认为(target === "ES6" ? "ES6" : "commonjs")
            "moduleResolution": "node",
            // 决定如何处理模块。"node"对应于Node.js/io.js
            "noEmitHelpers": false,
            // 不在输出文件中生成用户自定义的帮助函数代码,如 __extends
            // Do not generate custom helper functions like __extends in compiled output.
            // 默认为false
            "noErrorTruncation": true,
            // 不截断错误消息
            "noFallthroughCasesInSwitch": true,
            // 报告switch语句的fallthrough错误(即不允许switch的case语句贯穿)
            "noImplicitAny": true,
            // 在表达式和声明上有隐含的any类型时报错
            "noImplicitReturns": true,
            // 不是函数的所有返回路径都有返回值时报错
            "noImplicitThis": true,
            // 当this表达式的值为any类型的时候,生成一个错误
            "noImplicitUseStrict": false,
            // 模块输出中是否不包含"use strict"指令
            "noStrictGenericChecks": false,
            // 是否禁用在函数类型里对泛型签名进行严格检查
            "noUnusedLocals": true,
            // 若有未使用的局部变量则抛错
            "noUnusedParameters": true,
            // 若有未使用的参数则抛错
            "outDir": "build/distribution",
            "paths": {
                "*": [
                    "node_modules/*"
                ]
            },
            "preserveConstEnums": true,
            // 保留const和enum声明
            "pretty": true,
            // 使用颜色和上下文给错误和信息添加样式(实验性)
            "removeComments": true,
            // 删除所有注释,除了以/!*开头的版权信息
            "sourceMap": false,
            // 生成相应的 .map文件
            // 不能与inlineSourceMap同时指定
            "strict": true,
            // 启用所有严格类型检查选项。
            // 启用strict相当于启用
            // noImplicitAny,noImplicitThis,alwaysStrict,
            // strictBindCallApply,
            // strictNullChecks,
            // strictFunctionTypes,
            // strictPropertyInitialization
            "strictNullChecks": true,
            // 在严格的null检查模式下,
            // null和undefined值不包含在任何类型里,
            // 只允许用它们自己和any来赋值(undefined可以赋值到void除外)
            "strictFunctionTypes": false,
            //是否禁用函数参数双向协变检查
            "target": "ES3",
            // 指定ECMAScript目标版本
            // "ES3"(默认), "ES5", "ES6"/"ES2015",
            // "ES2016", "ES2017"或 "ESNext"
            "traceResolution": false
            // 生成模块解析日志信息
        },
        "include": [
            "src/**/*"
        ],
        "exclude": [
            "node_modules"
        ]
    }
    

    Step 3:创建Koa HelloWorld

    我们在src目录下创建文件server.ts

    import * as Koa from 'koa';
    import * as Router from 'koa-router';
    
    const app = new Koa();
    const router = new Router();
    
    router.get('/*', async (ctx) => {
        ctx.body = 'Hello Koa2 with TypeScript!';
    });
    
    app.use(router.routes());
    
    app.listen(3000);
    console.log('Server running on port 3000');
    

    Step 4:设置编译运行及热更新

    package.json中设置编译运行及热更新启动命令

        "scripts": {
            "boot-run": "tsc && node dist/server.js",
            "test": "nodemon --watch src -e ts,tsx --exec \"npm run boot-run\" "
        }
    

    其中npm run boot-run用于编译运行,npm test(或npm run test)用于开发过程中使用nodemon 监视源文件变化以热更新。完整的package.json例子如下。

    {
        "name": "koa2",
        "version": "2019.9.1",
        "description": "Koa2 application",
        "main": "index.js",
        "scripts": {
            "boot-run": "tsc && node dist/server.js",
            "test": "nodemon --watch src -e ts,tsx --exec \"npm run boot-run\" "
        },
        "repository": {
            "type": "git",
            "url": "http://localhost"
        },
        "author": "",
        "license": "MIT",
        "dependencies": {
            "koa": "^2.8.1",
            "koa-router": "^7.4.0",
            "tslib": "^1.10.0"
        },
        "devDependencies": {
            "@types/koa": "^2.0.49",
            "@types/koa-router": "^7.0.42",
            "nodemon": "^1.19.2",
            "typescript": "^3.6.3"
        }
    }
    

    TODO

    尚未加入tslint

    Reference

    1. 使用Typescript和Koa构建Node应用
      这篇文章配置nodemon监视源文件改变时命令有误,应该使用--watch src而不是UNIX通配符形式,阅读nodemon文档时发现了这一点
    2. nodemon
      https://github.com/remy/nodemon#nodemon

    相关文章

      网友评论

          本文标题:Koa 2+TypeScript简单配置

          本文链接:https://www.haomeiwen.com/subject/swheectx.html