详细记录开发一个npm包,封装前端常用的工具函数

4,055 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天

前言:

  1. 平常只是install别人开源的npm包,是不是自己也想搞一个呀,最起码知道整个流程是什么样的
  2. 前端开发中,会经常使用一些工具函数,项目直接来回拷贝,太麻烦了
  3. 鉴于如此,搞一个入门的前端工具函数npm包吧!学习+实用

仓库地址

🎸 npm 库   🌈 Github

整体流程

  1. 本地创建nodejs项目,使用rollup、typescript、jest等进行打包构建
  2. 提交代码至github
  3. 通过github action监听提交事件,执行jobs进行打包构建、并发布代码至npm远程库

image.png

开发npm包

创建项目

  1. 先给npm包起一个名字

    校验名字是否在npm库已经存在

    $ npm search dip-utils
    
    No matches found for "dip-utils"
    

    没有匹配到名字,说明包名可以使用

  2. 在github上创建仓库

image.png

  1. 克隆仓库到本地
  $ git clone https://github.com/kingfront/dip-utils.git
  $ cd dip-utils
  $ npm init
  package name: (tmp) dip-utils
  version: (1.0.0) 
  description: 前端工具函数
  entry point: (index.js) 
  test command: 
  git repository: 
  keywords: utils
  author: kinghao
  license: (ISC) MIT

package.json

  {
    "name": "dip-utils",
    "version": "1.0.0",
    "description": "前端工具函数",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [
      "utils"
    ],
    "author": "kinghao",
    "license": "MIT"
  }
  1. 创建项目目录
  • dip-utils
    • dist
    • example
    • src
    • test

到此为止,开发环境已经初步建好了,下面开始框架、代码开发

配置项目框架

框架依赖

  • 🍭 使用rollup 打包
  • 🍭 使用typescript 开发
  • 🍭 使用jest 单元测试
  • 🍭 使用eslint代码校验
  • 🍭 使用prettier代码格式化
  1. 配置支持typescript
  • 安装依赖

    $ npm install -D tslib @types/node
    
  • 项目根目录创建 tsconfig.json

    {
      "include": ["src/**/*/*.ts", "src/**/*.ts", "src/*.ts", "test/*.*.ts", "test/*/*.*.ts"],
      "output": "./dist/",
      "paths": {
        "src/*": ["src/*", "src/*/*"]
      },
      "compilerOptions": {
        "target": "es5",
        "moduleResolution": "node",
        "strict": true,
        "esModuleInterop": true,
        "useUnknownInCatchVariables": false
      }
    }
    
  1. 配置rollup

    • 安装依赖
    $ npm install -D rollup
    $ npm install -D rollup-plugin-node-resolve
    $ npm install -D @rollup/plugin-typescript
    
    • 项目根目录创建 rollup.config.js
    import resolve from 'rollup-plugin-node-resolve'
    import typescript from '@rollup/plugin-typescript'
    export default {
      input: './src/index.ts', // 入口文件
      output: [
        {
          format: 'cjs', // 打包为commonjs格式
          file: 'dist/dip-utils.cjs.js', // 打包后的文件路径名称
          name: 'dutils' // 打包后的默认导出文件名称
        },
        {
          format: 'esm', // 打包为esm格式
          file: 'dist/dip-utils.esm.js',
          name: 'dutils'
        },
        {
          format: 'umd', // 打包为umd通用格式
          file: 'dist/dip-utils.umd.js',
          name: 'dutils',
          minifyInternalExports: true
        }
      ],
      plugins: [typescript({ tsconfig: './tsconfig.json' }), resolve()]
    }
    
    • src目录下创建index.ts
    export function random(min: number, max: number): number {
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    
    • src目录下创建声明文件 index.d.ts
    declare namespace dipUtils {
      /**
       * 生成数字范围内的随机数
       * @param min 最小数字
       * @param max 最大数字
       * @returns number类型
       */
      export function random(min: number, max: number): number
    }
    
    declare module 'dip-utils' {
      export = dipUtils
    }
    
    • package.json 增加配置项
    {
      "name": "dip-utils",
      "version": "1.1.1",
      "description": "前端常用工具函数封装",
      "author": "kinghao",
      "license": "MIT",
    + "main": "dist/dip-utils.cjs.js",
    + "module": "dist/dip-utils.esm.js",
    + "browser": "dist/dip-utils.umd.js",
    + "types": "src/index.d.ts",
    + "files": [
    +   "src",
    +   "dist/*.js"
    + ],
      "scripts": {
    +   "build": "rollup -c"
      }
    }
    
    • 执行打包命令,测试

    image.png

    • 一个简单的函数已经打包成功了,并输出了3种不同的格式

    image.png

  2. 配置jest单元测试

  • 安装依赖

    $ npm install -D @types/jest babel-jest jest @babel/core @babel/preset-env @babel/preset-typescript
    
  • 跟目录下创建文件 jest.conf.js

    module.exports = {
      transform: {},
      testEnvironment: 'jsdom',
      extensionsToTreatAsEsm: ['.ts'],
      moduleFileExtensions: ['js', 'json', 'jsx', 'node', 'ts']
    }
    
  • 跟目录下创建文件 babel.config.js

    module.exports = {
      presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript']
    }
    
  • package.json 增加test脚本

    "scripts": {
       + "test": "jest",
     }
    
  • test目录下创建 index.test.ts

    import { random } from '../src/index'
    describe('生成数字范围内的随机数', () => {
      it('random(1, 1) -> should return 1', () => {
        const rand = random(1, 1)
        expect(rand).toBe(1)
      })
      it('random(1, 10) -> should return number', () => {
        const rand = random(1, 10)
        expect(rand).toBeNaN
      })
    })
    
  • 执行测试命令

    npm run test
    

    image.png

创建npm账号

  1. 前往npm官网创建 www.npmjs.com

  2. 个人中心-创建Access Tokens

    创建一个名字为npm_token的Tokens

    image.png

  3. 保存并复制 npm_token 的值,下面github action里面需要使用tokens值

    image.png

  4. 前往github 项目仓库,配置Actions secrets

    image.png

  5. 配置npm_token,并把刚才生成的值复制到value里,点击新增 image.png

配置github action

  1. 创建 workflows

    在github 项目仓库的Actions下

    image.png

  2. 修改npm-publish.yml,并提交保存

    image.png

    修改如下:

    # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
    # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
    
    name: Node.js Package
    
    on:
      push:
        branches:
          - master
    
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - uses: actions/setup-node@v3
            with:
              node-version: 16.x
          - run: npm i
          - run: npm run test
    
      publish-npm:
        needs: build
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - uses: actions/setup-node@v3
            with:
              node-version: 16.x
              registry-url: https://registry.npmjs.org/
          - run: npm publish
            env:
              NODE_AUTH_TOKEN: ${{secrets.npm_token}}
    
    • on push branches master :表示只要往master上提交代码,就执行action操作,发布到npm远程仓库
    • jobs build:构建任务,进行执行安装依赖、单元测试
    • jobs publish-npm:进行远程推送到npm仓库操作
    • 详细配置请参考github actions文档

发布npm包

  • 提交代码至github仓库,就能触发github actions 进行远程发布npm包了

发布成功,actions可实时查看执行的进度、日志

image.png

发布成功,前往npm官网查看package,已经发布成功了

image.png

注:每次提交都会触发npm发布的,package.json里面的version版本每次需要手动修改,否则会发布失败的

结尾

ok, 到这里就先告一段落了

完整的 前端工具函数库请前往:

源码仓库地址:github.com/kingfront/d…

npm库地址:www.npmjs.com/package/dip…

记得给点个start哦