1. 程式人生 > >在2018年如何優雅的開發一個typescript語言的npm包?

在2018年如何優雅的開發一個typescript語言的npm包?

order pts 文件夾 pub epub save rip ring 回復

歡迎大家前往騰訊雲+社區,獲取更多騰訊海量技術實踐幹貨哦~

本文由小明plus發表

很多時候,我們可能想要用 typescript 語言來創建一些模塊,並提交到 npm 供別人使用,

那麽在 2018 年,如果我想要初始化這樣的一個模塊,我需要做哪些步驟呢?

答案是:創建一個優雅的,對開發者友好的模塊,至少需要以下 15 個步驟

  1. 初始化文件夾,初始化 git 倉庫,初始化 npm,初始化 tsc
  2. 修改 tsconfig.js 配置
  3. 添加 npm 腳本
  4. 添加 tslint 校驗代碼規則以及 editorconfig,prettier 統一代碼風格
  5. 設置 git 提交的校驗鉤子
  6. 開始編寫代碼
  7. watch 模式開發
  8. 忽略 ts 編譯生成的文件夾
  9. 添加單元測試
  10. 寫一個單元測試示例
  11. 設置一些有用的 npm 腳本
  12. 完善 package.json 的描述信息
  13. 提交代碼到 git 倉庫
  14. 發布包到 npm

本篇文章裏,我會列出每個步驟的詳細說明。

實際開發中,如果每個包都去走一遍這些步驟,步驟好像確實有點多。所以如果你需要實際創建項目的時候,你可以選擇 clone 我提供的樣板項目 來開始一個新的 ts 模塊的開發,主要步驟如下:

git clone https://github.com/xiaomingplus/npm-typescript-boilerplate.git your-project-name
cd your-project-name
# 安裝依賴
npm i
# 開始開發
npm start
# 修改 package.json 裏面的項目名和簡介
# 修改 README.md 文件內容
# 修改 遠程倉庫的地址
git remote set-url origin your-git-url

下面就是常規步驟了,學習目的的話,建議按照下面的步驟全部跑一遍:

1. 初始化文件夾,初始化 npm,初始化 tsc

mkdir project-name
cd project-name
# 初始化git項目
git init
# 添加gitignore文件
touch .gitignore
# 復制這個地址的ignore內容到.gitignore <https://github.com/github/gitignore/blob/master/Node.gitignore>

# 添加readme文件
echo "# My Awesome Typescript Project" >> README.md
# 安裝typescript
npm install --save-dev typescript
# 初始化npm包
npm init --y
# 初始化tsconfig
tsc --init

2. 修改 tsconfig.js 配置

修改以下默認配置:

{
    "compilerOptions": {
        "declaration": true,
        "outDir": "./lib",
     },
    "include": ["src"],
    "exclude": ["node_modules", "**/__tests__/*"]
}

最終的 tsconfig 配置如下:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": true,
        "strict": true,
        "outDir": "./lib",
        "esModuleInterop": true
    },
    "include": ["src"],
    "exclude": ["node_modules", "**/__tests__/*"]
}

3. 添加 npm 腳本

在 package.json 裏編輯 scripts 字段:

{
  "scripts": {
    "start": "tsc -w",
    "build": "tsc"
  }
}

4. 添加 tslint 校驗代碼規則以及 editorconfig,prettier 統一代碼風格

npm install --save-dev prettier tslint tslint-config-prettier

新建tslint.json文件

{
  "extends": ["tslint:recommended", "tslint-config-prettier"],
  "rules": {
    "no-console": false,
    "object-literal-sort-keys": false,
    "member-access": false,
    "ordered-imports": false
  },
  "linterOptions": {
    "exclude": ["**/*.json", "node_modules"]
  }
}

新建 .prettierrc 文件

{
  "trailingComma": "all",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true,
  "endOfLine": "lf",
  "printWidth": 120,
  "overrides": [
    {
      "files": ["*.md", "*.json", "*.yml", "*.yaml"],
      "options": {
        "tabWidth": 2
      }
    }
  ]
}

新建 .editorconfig

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = space
indent_size = 4

[{*.json,*.md,*.yml,*.*rc}]
indent_style = space
indent_size = 2

添加一個便捷的 scripts 腳本:

{
  "scripts": {
    "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
    "lint": "tslint -p tsconfig.json"
  }
}

5. 設置 git 提交的校驗鉤子

設置 git 提交的鉤子校驗規範

npm install --save-dev husky @commitlint/config-conventional @commitlint/cli commitizen cz-conventional-changelog

新建 commitlint.config.js 文件

touch commitlint.config.js

寫入:

module.exports = {
  extends: ["@commitlint/config-conventional"]
};

新建 .huskyrc 文件

touch .huskyrc

寫入:

{
    "hooks": {
        "pre-commit": "npm run format && npm run lint && npm test",
        "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
}

新建配置文件:

touch .czrc

寫入配置:

{ "path": "cz-conventional-changelog" }

package.json 新增 scripts 配置:

{
  "scripts": {
    "commit": "git-cz"
  }
}

6. 開始編寫代碼

cd project-name
mkdir src
cd src
touch index.ts

寫下你的第一行 ts 代碼:

export const Greeter = (name: string) => `Hello ${name}`;

7. watch 模式下開發

npm start

8. 忽略 ts 編譯生成的文件夾

/lib文件夾添加到.gitignore

/lib

9. 添加單元測試

npm install --save-dev jest ts-jest @types/jest

創建 jestconfig.json文件:

{
  "transform": {
    "^.+\\.(t|j)sx?$": "ts-jest"
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
  "moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"]
}

修改 package.json 裏的 scripts 下的 test :

{
  "scripts": {
    "test": "jest --config jestconfig.json"
  }
}

10. 寫一個單元測試示例

src 文件夾下新建一個 __tests__的文件夾來存放測試用例文件,新建一個 Greeter.test.ts文件,寫入:

import { Greeter } from "../index";
test("My Greeter", () => {
  expect(Greeter("Carl")).toBe("Hello Carl");
});

運行測試用例:

npm test

結果應該是通過的。

11. 設置一些有用的 npm 腳本

prepare: 發布前和用戶安裝前運行

prepublishOnly: 發布前運行

preversion: 新建一個版本前運行

version: 新建一個版本後運行

postversion: 新建版本後運行

{
  "scripts": {
    "prepare": "npm run build",
    "prepublishOnly": "npm test && npm run lint",
    "preversion": "npm run lint",
    "version": "npm run format && git add -A src",
    "postversion": "git push && git push --tags"
  }
}

12. 完善 package.json 的描述信息

name 完善包名,描述,包入口文件 main 字段,typescript 類型文件 types 字段定義

{
    "name": "project-name"
    "description": "A nice greeter",
    "main": "lib/index.js",
    "types": "lib/index.d.ts"
}

13. 完善文檔信息

新建 doc 文件夾,在裏面可以寫一些模塊詳細的文檔:

mkdir doc

完善 readme.md的信息,格式可以參考 這裏

14. 提交代碼到 git 倉庫

發布之後就把代碼提交到 git 倉庫吧

git add .
git commit -m "feat: init"
# 關聯到遠程倉庫不屬於本教程的內容,就不寫push了

15. 發布包到 npm

如果你還沒註冊 npm 的用戶的話,需要先註冊。

npm adduser

註冊好之後就可以發布到 npm 了:

# 自動修改package.json文件版本號+1
npm version patch
npm publish

發布之後,你可以去 <https://www.npmjs.com/> 上找到你的包

參考

Step by step: Building and publishing an NPM Typescript package.

此文已由作者授權騰訊雲+社區發布,更多原文請點擊

搜索關註公眾號「雲加社區」,第一時間獲取技術幹貨,關註後回復1024 送你一份技術課程大禮包!

在2018年如何優雅的開發一個typescript語言的npm包?