返回

用TDD的方式写一个package(下)

前端

theme: channing-cyan ---

上文我们已经完整的写了一个add函数和测试用例,还记得我们的目标吗?

接着继续吧。。。

1. 发布到npm仓库,可通过`pnpm install @xx/package-name`进行安装。

```shell
# npm发布
npm publish --access=public

# pnpm发布
pnpm publish --registry=https://registry.npmjs.org

# yarn发布
yarn publish --access=public
```

2. 在项目中使用

```ts
// 假设发布到npm仓库后,在另一个项目中引用
import { add } from '@xx/package-name';

const result = add(1, 2);
console.log(result); // 3
```

3. 单元测试

```ts
// 单元测试
import { add } from '../src/index';

describe('add', () => {
  it('should return the sum of two numbers', () => {
    expect(add(1, 2)).toBe(3);
    expect(add(-1, -2)).toBe(-3);
    expect(add(1.5, 2.5)).toBe(4);
  });
});
```

4. 代码覆盖率

```shell
# 查看代码覆盖率
npx nyc report
```

5. 持续集成

```yaml
# .github/workflows/ci.yaml
name: CI

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '16'
      - run: npm install
      - run: npm run build
      - run: npm test
```

6. 文档

```
# README.md
## package-name

A simple package for adding two numbers.

### Installation

```shell
npm install @xx/package-name
```

### Usage

```ts
import { add } from '@xx/package-name';

const result = add(1, 2);
console.log(result); // 3
```

### API

#### add(a, b)

Returns the sum of two numbers.

* **a** : The first number.
* **b** : The second number.

### Testing

```shell
npm test
```

### License

MIT
```

通过以上步骤,我们就完成了一个简单的package的编写和发布,是不是很简单呢?

最后,希望这篇文章对您有所帮助,如果您有任何问题或建议,欢迎在评论区留言。

参考资料:

SEO关键词:

用TDD的方式写一个package的详细教程,包括发布到npm仓库、在项目中使用、单元测试、代码覆盖率、持续集成、文档等内容。