随着我们的项目增多,代码量剧增,为了更好的提高开发效率,并且能从以往做过的项目中提取出可重复使用的函数/模块,提高代码复用性和可维护性,开发一个长久维护的sdk和组件库是必不可少的。这里将给出一个使用typescript搭建sdk的流程说明。
使用技术栈:
- typescript 编写sdk主要代码
- gulp 打包sdk
- jest 测试用例
创建项目
创建文件夹,进入文件夹,使用 npm init 指令添加package.json配置
package name: (wuli-sdk) // npm包名(和项目文件夹同名,可以回车略过)
version: (1.0.0) // npm包版本号(可回车略过)
description: sdk demo // 包描述(可回车略过)
entry point: (index.js) // 入口文件(默认index.js,可回车略过)
test command: // 测试的指令(可回车略过)
git repository: // git仓库地址(可回车略过)
keywords: // npm包的搜索关键词(可回车略过)
author: WULIbinbin // 作者名称(可回车略过)
license: (ISC) // 使用证书(可回车略过)
Is this OK? (yes) yes // 输入yes
安装依赖
npm i -g typescript gulp-cli
npm i -D gulp gulp-typescript jest @types/jest ts-jest
项目目录
创建src文件夹,添加index.ts作为sdk的入口,目录如下:
__tests__ // jest测试用例文件存放
---index.test.js
lib // sdk 打包后文件
src // sdk主要代码
---index.ts
.npmignore // 发布时忽略的文件
gulpfile.js // gulp执行函数
jest.config.js // jest配置
package.json // npm依赖配置
tsconfig.json // typescript配置
添加配置
添加typescript配置,根目录tsconfig.json
{
"compilerOptions": {
"target": "ES5", // 或ES6
"module": "commonjs", // 或ES6
"outDir": "lib", // 编译文件导出至lib文件夹
"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
}
添加gulp配置,在根目录gulpfile.js
const gulp = require('gulp');
const ts = require('gulp-typescript');
// 根据tsconfig将编译后的文件打包复制到lib文件
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);
修改package.json
- 将main入口改成编译后lib里的index.js
- 新增
build:lib指令,用于删除lib文件夹并执行gulpfile - 新增
test指令,用于单元测试
{
"name": "your-sdk",
"version": "1.0.0",
"description": "sdk demo",
"main": "lib/index.js", // 1
"scripts": {
"build:lib": "rimraf lib && gulp build", // 2 (windows删除用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"
}
}
添加sdk代码
在src/index.ts中导出一个类,当项目引入了sdk后,可以通过new Sdk()获取实例化对象,示例:
// 定义sdk需要传入的config参数类型(非必须,请根据项目需求添加)
interface IConfig {
domain:string,
appid:string,
}
export default class Sdk {
config = null
constructor(config:IConfig) {
// 将config保存于对象中
this.config = config;
}
sayHi() {
return "HI";
}
sayHiAsync() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("HI");
}, 1000);
});
}
}
尝试使用npm run build:lib运行gulp打包代码
// 在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
可以看到根目录的lib文件夹有更新文件,代表打包成功
验证sdk
在根目录的jest.config.js,添加jest配置
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
};
在根目录的__tests__文件夹新增index.test.ts
// 引入已打包的sdk
import Lib from "../lib/index";
test("install sdk success", () => {
const params = {
domain: "https://www.baidu.com",
appid: "wx123456789",
};
// 实例化sdk对象
const sdk = new Lib(params);
console.log(sdk);
// 测试sayHi
expect(sdk.sayHi()).toBe('HI')
sdk.sayHiAsync().then(res=>{
expect(res).toBe('HI')
})
});
输入npm run test开始测试,没有报错则测试成功,sdk可用
> 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:11)
PASS __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.
发布至npm
在根目录添加.npmignore文件,发布npm时可以忽略以下代码
node_modules
src
__test__
.gitignore
.npmrc
babel.config.js
tsconfig.json
yarn.lock
gulpfile.js
.vscode
在package.json中添加publish指令
{
"scripts": {
"publish": "npm publish --registry=https://registry.npmjs.org/",
}
}
使用npm adduser添加npm账号,然后执行npm run publish发布至npm,当在npm绑定的邮箱会提示发布成功。
附github链接:github.com/WULIbinbin/…