Visual Studio + TypeScript + Jest 專案要Publish 到 NPM 除雷教學 一步一步

最近我把 Nodejs 專案轉成 TypeScript,發現原本的步驟都要做些修改阿 這邊紀錄一下我除雷的過程

tsconfig.json 修改

  1. 如果在 /tsconfig.json 不存在這個檔案 請建立.
  2. 修改資料如下
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "declaration": true,
    "outDir": "./lib",
    "lib": [ "es6" ],
    "sourceMap": true
  },
  "exclude": [
    "node_modules", "**/__tests__/*","lib"
  ]
}


Visual Studio Project Properties





  1. 記得 startuo file 要修改成 lib/<啟動的檔名>.ts  這樣才能啟動

Jest Config

  1. 安裝 npm install --save-dev jest ts-jest @types/jest
  2. 創立 jestconfig.json 內容如下.
{
  "transform": {
    "^.+\\.(t|j)sx?$": "ts-jest"
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
  "moduleFileExtensions": [ "ts", "tsx", "js", "jsx", "json", "node" ],
  "coverageDirectory": "./coverage/",
  "roots": ["./test"],
  "collectCoverage": true
}
Note roots 要設定不然同個 test 會跑兩次
5. 刪掉原本 package.json   中的的 test  script 換成新的 : "test": "jest --config jestconfig.json",

6. 因為我們設定 test 的命名規則是  __tests__  所以名稱應該是要 ***.tests.ts

example. 我們創建一個 Greeter.test.ts 內容如下

Greeter.test.ts
Now, Try to run
npm test

index.ts

  1. 創建 npm 套件 引用索引物件 /index.ts
  2. 內容類似如下 (請照自己的要開放的物件為主)
import { Config } from "./Config"
import { Warder } from "./warder/Warder";
import { ReactiveGener } from "./run/ReactiveGener";
import { BZKLauncher } from "./run/BZKLauncher";
import { Runer } from "./run/Runer";
import { UntilsUtils } from "./UntilsUtils";
import { Action } from "./comm/delegate/Action";
import { ActionT1 } from "./comm/delegate/ActionT1";
import { FuncT1 } from "./comm/delegate/FuncT1";
import { OOAction } from "./comm/delegate/OOAction";
import { OOActionT1 } from "./comm/delegate/OOActionT1";


export {
    Config, Warder, ReactiveGener, BZKLauncher, Runer, UntilsUtils,
    Action, ActionT1, FuncT1, OOAction, OOActionT1
}
  1. 使用該物件的 import 如下
import { Config , Warder } from "<你的npm套件名稱>";

package.json

{
  "name": "<你的npm套件名稱>",
  "version": "0.0.6",
  "description": "AutoTradeBazookaFramework",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",
  "author": "Kirin",
  ...
}

  1. main 和 types 請記得修改 , 其他都與之前上傳 npm 該注意的一樣

跟之前一樣 npm publish

留言

  1. Water Hack Burns 2lb of Fat OVERNIGHT

    At least 160 thousand women and men are losing weight with a easy and secret "water hack" to lose 2 lbs each night in their sleep.

    It's painless and it works with everybody.

    This is how to do it yourself:

    1) Get a glass and fill it with water half full

    2) And then follow this amazing hack

    so you'll become 2 lbs thinner the very next day!

    回覆刪除

張貼留言

這個網誌中的熱門文章

angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學