Nodejs 使用 TypeScript
阅读原文时间:2023年07月08日阅读:1
  1. 安装依赖

    λ yarn add typescript types/node concurrently nodemon wait-on -D

  2. 初始化一个 tsconfig.json

    λ ./node_modules/.bin/tsc --init

  3. 编写 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"]
    }

  4. 创建 tsconfig.build.json

    {
    "extends": "./tsconfig.json",
    "exclude": ["node_modules", "dist"]
    }

  5. 创建 nodemon.json

    {
    "watch": ["dist"],
    "ext": "js",
    "exec": "node dist/index"
    }

  6. 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

  • 安装jest的vscode插件也行
  1. 安装依赖

    λ npm i -D @types/jest jest ts-jest ts-node

  2. 增加scripts

    "scripts": {

    "test": "jest",
    "coverage": "jest --coverage"
    }

  3. 设置VScode的launch.json

    {
    "version": "0.2.0",
    "configurations": [
    {
    "type": "node",
    "request": "launch",
    "name": "Jest Current File",
    "skipFiles": [
    "/" ], "program": "${workspaceFolder}/node_modules/.bin/jest", "args": [ "${relativeFile}" ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "outFiles": [ "${workspaceFolder}//*.js"
    ],
    "windows": {
    "program": "${workspaceFolder}/node_modules/jest/bin/jest"
    }
    }
    ]
    }

  4. 设置配置文件jest.config.js

    module.exports = {
    transform: { "^.+\.ts?$": "ts-jest" },
    testEnvironment: "node",
    testRegex: "/test/.*\.(test|spec)?\.(ts|tsx)$",
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
    };

  5. 添加测试脚本 /test/test.test.ts

    it("tobe", () => {
    expect("asd").toBe("asd");
    });

  6. 运行测试

    npm t

可以单独的运行ts文件,而无需编译

λ npm i -g ts-node
λ ts-node index.ts
hello ts

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章