With the increase of our projects and the increase of code volume, it is essential to develop a long-term maintenance SDK and component library in order to better improve development efficiency and extract reusable functions/modules from previous projects to improve code reusability and maintainability. Here is a process for building an SDK using typescript.

Using the Technology stack:

  • Typescript writes the main SDK code
  • Gulp packaging SDK
  • Jest test case

Create a project

Create a folder, go to the folder, and add the package.json configuration using the NPM init directive

package name: (wuli-sdk) // NPM package name (same as project folder name, can be omitted by press enter)
version: (1.0. 0) // NPM package version number
description: sdk demo // Package description (enter to skip)
entry point: (index.js) // Entry file (default index.js, can be skipped by enter)
test command: // Test the command (can be skipped by enter)
git repository: // Git repository address
keywords: // Search keyword for NPM package
author: WULIbinbin // Author name (enter to skip)
license: (ISC) // Use the certificate (enter to skip)
Is this OK? (yes) yes Yes / / input
Copy the code

Install dependencies

npm i -g typescript gulp-cli
npm i -D gulp gulp-typescript jest @types/jest ts-jest
Copy the code

Project directory

Create a SRC folder and add index.ts as the SDK entry directory as follows:

__tests__ // Jest test case file store
---index.test.js
lib // SDK packaged file
src // SDK main code
---index.ts
.npmignore  // Files ignored when publishing
gulpfile.js // gulp executes the function
jest.config.js / / jest configuration
package.json // NPM depends on configuration
tsconfig.json / / typescript configuration
Copy the code

Add the configuration

Add the typescript configuration to the tsconfig.json root directory

{
    "compilerOptions": {
        "target": "ES5"./ / or ES6
        "module": "commonjs"./ / or ES6
        "outDir": "lib".// Compile the file and export it to the lib folder
        "noUnusedLocals": false."noUnusedParameters": false."strictNullChecks": false."sourceMap": true."baseUrl": "src"."rootDir": "src"."esModuleInterop": true."skipLibCheck": true."removeComments": true."preserveConstEnums": true."moduleResolution": "node"."strict": false."experimentalDecorators": true."noImplicitAny": false."allowSyntheticDefaultImports": true."allowJs": true."resolveJsonModule": true."declaration": true
    },
    "include": ["src/**/*"]."exclude": ["node_modules"."__tests__"]."compileOnSave": false
}

Copy the code

Add the gulp configuration to the root directory gulpfile.js

const gulp = require('gulp');
const ts = require('gulp-typescript');
// Package and copy the compiled files to the lib file according to tsconfig
const tsProject = ts.createProject('./tsconfig.json');
function tsc(cb) {
    gulp.src('./src/**/*.{ts,tsx}').pipe(tsProject())
    .pipe(gulp.dest('./lib'));
    cb();
}

exports.build = gulp.series(tsc);
Copy the code

Modify the package. The json

  1. Change the main entry to index.js in the compiled lib
  2. newbuild:libCommand to delete the lib folder and execute gulpfile
  3. newtestInstruction for unit testing

{
    "name": "your-sdk"."version": "1.0.0"."description": "sdk demo"."main": "lib/index.js"./ / 1
    "scripts": {
        "build:lib": "rimraf lib && gulp build".// 2 (Windows delete with rmdir lib)
        "test": "jest" / / 3
    },
    "author": "yourname"."license": "ISC"."dependencies": {},
    "devDependencies": {
        "@types/jest": "^ 27.0.2"."gulp": "^ 4.0.2." "."gulp-typescript": "6.0.0 - alpha. 1"."jest": "^ 27.3.1"."ts-jest": "^ 27.0.5"."typescript": "4.4.4"}}Copy the code

Adding SDK code

Export a class in SRC /index.ts. When the project introduces the SDK, you can get the instantiation object via new SDK (). Example:

// Define the type of config parameters that the SDK needs to pass in (optional, please add according to the project requirements)
interface IConfig {
    domain:string,
    appid:string,
}

export default class Sdk {

    config = null

    constructor(config:IConfig) {
        // Save config in the object
        this.config = config;
    }

    sayHi() {
        return "HI";
    }

    sayHiAsync() {
        return new Promise((resolve) = > {
            setTimeout(() = > {
                resolve("HI");
            }, 1000); }); }}Copy the code

Try running gulp packaging code using NPM run build:lib

Type in CMD /bash

npm run build:lib

> wuli-sdk@1.0. 0 build:lib /Users/wuzhuobin/Desktop/github/wuli-sdk
> rimraf lib && gulp build

Using gulpfile ~/Desktop/github/wuli-sdk/gulpfile.js

Starting 'build'. Starting'tsc'. Finished'tsc' after 10 ms
Finished 'build' after 12 ms
Copy the code

You can see that there are update files in the lib folder of the root directory, indicating successful packaging

Verify the SDK

In the root directory of jest. Config. js, add jest configuration

module.exports = {
    preset: "ts-jest".testEnvironment: "jsdom"};Copy the code

Add index.test.ts to the __tests__ folder in the root directory


// Import the packaged SDK
import Lib from ".. /lib/index";

test("install sdk success".() = > {
    const params = {
        domain: "https://www.baidu.com".appid: "wx123456789"};// Instantiate the SDK object
    const sdk = new Lib(params);
    console.log(sdk);
    / / test sayHi
    expect(sdk.sayHi()).toBe('HI')
    sdk.sayHiAsync().then(res= >{
        expect(res).toBe('HI')})});Copy the code

Enter NPM run test to start the test. If no error is reported, the test succeeds and the SDK is available

> wuli-sdk@1.0. 0 test
/wuli-sdk
> jest

console.log
Sdk {
config: { domain: 'https://www.baidu.com'.appid: 'wx123456789' }
}

at Object.<anonymous> (__tests__/index.test.ts:9:11PASS __tests__/index.test.ts ✓ Install SDK success (17 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.115 s
Ran all test suites.
Copy the code

Release to NPM

Add the. Npmignore file to the root directory, and you can ignore the following code when publishing NPM

node_modules
src
__test__
.gitignore
.npmrc
babel.config.js
tsconfig.json
yarn.lock
gulpfile.js
.vscode
Copy the code

Add a publish directive to package.json

{
    "scripts": {
        "publish": "npm publish --registry=https://registry.npmjs.org/",}}Copy the code

Run the NPM adduser command to add the NPM account, and then run the NPM run publish command to publish to NPM. If the mailbox bound to NPM is displayed, the publication will be successful.