使用 TypeScript 建立 npm 套件

建立專案

1
mkdir ts-example-package

使用以下指令建立 package.json 檔:

1
npm init

生成後 package.json 檔如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"name": "@memochou1993/ts-example-package",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/memochou1993/ts-example-package.git"
},
"author": "Memo Chou",
"license": "ISC",
"bugs": {
"url": "https://github.com/memochou1993/ts-example-package/issues"
},
"homepage": "https://github.com/memochou1993/ts-example-package#readme"
}

安裝 TypeScript 和 Jest 測試套件。

1
npm i -D typescript jest ts-jest @types/jest

建立 tsconfig.json 檔:

1
2
3
4
5
6
7
8
9
10
11
12
{
"compilerOptions": {
"outDir": "dist",
"lib": [
"es2016",
],
"sourceMap": true
},
"include": [
"src/**/*.ts"
]
}
  • 參數 compilerOptions.outDir 指定生成的 JavaScript 檔所放置的位置。
  • 參數 compilerOptions.lib 表示 ES6 語法是可被使用的。
  • 參數 include 指定要被編譯的檔案。

package.json 檔的腳本中,加入以下指令:

1
2
3
4
5
6
{
"scripts": {
"build": "tsc",
"test": "jest"
},
}

src 資料夾新增 index.ts 檔,並新增主要程式碼。

1
2
3
export function hello(name: string): string {
return `Hello ${name}`;
}

執行編譯。

1
npm run build

編譯後的 JavaScript 檔在 dist 資料夾裡,內容如下:

1
2
3
4
5
6
7
8
"use strict";
exports.__esModule = true;
exports.hello = void 0;
function hello(name) {
return "Hello " + name;
}
exports.hello = hello;
//# sourceMappingURL=index.js.map

單元測試

test 資料夾新增 index.test.ts 檔:

1
2
3
4
5
import { hello } from '../src';

test('hello', () => {
expect(hello('World')).toEqual('Hello World');
});

建立 Jest 設定檔:

1
node_modules/.bin/ts-jest config:init

建立的 jest.config.js 檔如下:

1
2
3
4
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};

執行測試。

1
npm run test 

發布套件

建立 .gitignore 檔,並推送至 GitHub。

1
2
dist/
node_modules/

修改 package.json 檔,指定只有 dist 資料夾中的內容需要被發布。

1
2
3
4
5
6
{
"main": "dist/index.js",
"files": [
"dist"
]
}

測試發布,查看即將發布的檔案列表。

1
npm publish --dry-run

登入 npm 套件管理平台。

1
npm login

發布套件。

1
npm publish --access=public

參考資料