Make writing a habit together! This is the first day I participated in the “Dig gold Day New Plan ยท April More text challenge”

Preface:

  1. Usually just install other people’s open source NPM package, do you want to make a own ah, at least know the whole process is what
  2. Front-end development, will often use some tool functions, the project directly back and forth copy, too troublesome
  3. For that reason, get an NPM package for getting started with front-end utility functions.Learning + Practical

The warehouse address

๐ŸŽธ NPM library ๐ŸŒˆ Github

The whole process

  1. Create nodeJS projects locally and package them with rollup, typescript, Jest, etc
  2. Submit code to Github
  3. The Github Action listens for commit events, executes jobs for package builds, and publishes code to the NPM remote library

The development of NPM package

Create a project

  1. Start by giving the NPM package a name

    Verify that the name already exists in the NPM library

    $ npm search dip-utils
    
    No matches found for "dip-utils"
    Copy the code

    If no name is matched, the package name is available

  2. Create the repository on Github

  1. Clone the warehouse locally
  $ git clone https://github.com/kingfront/dip-utils.git
  $ cd dip-utils
  $ npm initPackage name: (TMP) dip-utils version: (1.0.0) Description: Front-end tool function Entry Point: (index.js) test command: git repository: keywords: utils author: kinghao license: (ISC) MITCopy the code

package.json

  {
    "name": "dip-utils"."version": "1.0.0"."description": "Front-end utility functions"."main": "index.js"."scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [
      "utils"]."author": "kinghao"."license": "MIT"
  }
Copy the code
  1. Create a project directory
  • dip-utils
    • dist
    • example
    • src
    • test

So far, the development environment has been preliminarily set up, so let’s start framework and code development

Configure the project framework

Frame dependence

  • ๐Ÿญ package using rollup
  • ๐Ÿญ develop with typescript
  • ๐Ÿญ Use jEST unit tests
  • ๐Ÿญ Verify using ESLint code
  • ๐Ÿญ uses the prettier code for formatting
  1. Configure support for typescript
  • Install dependencies

    $ npm install -D tslib @types/node
    Copy the code
  • Tsconfig.json is created in the project root directory

    {
      "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}}Copy the code
  1. Configure a rollup

    • Install dependencies
    $ npm install -D rollup
    $ npm install -D rollup-plugin-node-resolve
    $ npm install -D @rollup/plugin-typescript
    Copy the code
    • The project root directory creates rollup.config.js
    import resolve from 'rollup-plugin-node-resolve'
    import typescript from '@rollup/plugin-typescript'
    export default {
      input: './src/index.ts'.// Import file
      output: [{format: 'cjs'.// Package in commonJS format
          file: 'dist/dip-utils.cjs.js'.// The path name of the packaged file
          name: 'dutils' // The default exported file name after packaging
        },
        {
          format: 'esm'.// Package in ESM format
          file: 'dist/dip-utils.esm.js'.name: 'dutils'
        },
        {
          format: 'umd'.// Package to umD common format
          file: 'dist/dip-utils.umd.js'.name: 'dutils'.minifyInternalExports: true}].plugins: [typescript({ tsconfig: './tsconfig.json' }), resolve()]
    }
    Copy the code
    • SRC directory to create index.ts
    export function random(min: number, max: number) :number {
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    Copy the code
    • SRC directory to create the declaration file index.d.ts
    declare namespace dipUtils {
      /** * Generates a random number within the number range *@param Min Minimum number *@param Max Indicates the maximum number *@returns * / number type
      export function random(min: number, max: number) :number
    }
    
    declare module 'dip-utils' {
      export = dipUtils
    }
    Copy the code
    • Package. json adds configuration items
    {
      "name": "dip-utils"."version": 1.1.1 ""."description": "Front-end common tool function encapsulation"."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"}}Copy the code
    • Execute the package command and test

    • A simple function has been packagedsuccessful, and output three different formats

  2. Configure jEST unit tests

  • Install dependencies

    $ npm install -D @types/jest babel-jest jest @babel/core @babel/preset-env @babel/preset-typescript
    Copy the code
  • Create the jest. Conf.js file in the same directory

    module.exports = {
      transform: {},
      testEnvironment: 'jsdom'.extensionsToTreatAsEsm: ['.ts'].moduleFileExtensions: ['js'.'json'.'jsx'.'node'.'ts']}Copy the code
  • Create file babel.config.js in the same directory

    module.exports = {
      presets: [['@babel/preset-env', { targets: { node: 'current'}}].'@babel/preset-typescript']}Copy the code
  • Package. json adds the test script

    "scripts": {+"test": "jest",}Copy the code
  • Create index.test.ts in the test directory

    import { random } from '.. /src/index'
    describe('Generate random numbers in number range'.() = > {
      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
      })
    })
    Copy the code
  • Execute test command

    npm run test
    Copy the code

Create an NPM account

  1. Go to the NPM website to create www.npmjs.com

  2. Personal Center – Create Access Tokens

    Create a token called NPM_token

  3. Save and copy the tokens value of nPM_token

  4. Go to the Github project repository and configure Actions Secrets

  5. Configure nPM_token and copy the generated value into value. Click Add

Configuration is making the action

  1. To create workflows

    Under Actions in the Github project repository

  2. Modify npm-publish.yml and commit to save

    Modified as follows:

    # 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}}
    Copy the code
    • On Push Branch Master: Execute action whenever submit code to Master, publish to NPM remote warehouse
    • Jobs Build: Build task that performs installation dependencies and unit tests
    • Jobs publish-npm: Perform remote push to the NPM repository
    • Refer to the Github Actions document for details

Release NPM package

  • Submitting the code to the Github repository triggers Github Actions to publish the NPM package remotely

After the publication is successful, actions can view the execution progress and logs in real time

Successful release, go to NPM official website to view package, it has been successfully released

Note: Each commit will trigger NPM release. The version in package.json needs to be manually modified each time, otherwise the release will fail

At the end

Ok, that’s it for now

A complete library of front-end utility functions can be found at:

Source repository address: github.com/kingfront/d…

NPM library address: www.npmjs.com/package/dip…

Make sure you give me a start