前端初学者 sdk 的使用
迪丽瓦拉
2024-06-01 00:41:22
0

目录结构:

 package.json

{"name": "ivanfor666","version": "1.0.0","description": "","main": "dist/index.cjs.js","module": "dist/index.esm.js","browser": "dist/index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","build-pro": "rollup --config pro.config.js","build-sdk": "rollup --config sdk.config.js","build": "rollup --config sdk.config.js && rollup --config pro.config.js"},"keywords": ["前端","sdk"],"author": "","files": ["dist"],"license": "ISC","devDependencies": {"rollup": "^2.76.0","rollup-plugin-dts": "^4.2.2","rollup-plugin-typescript2": "^0.32.1","typescript": "^4.7.4"},"dependencies": {"@rollup/plugin-commonjs": "^24.0.1"}
}

创建好上面的 package.json 文件

执行 npm  i 安装好依赖

sdk.config.js

import ts from 'rollup-plugin-typescript2'
import path from 'path'
import dts from 'rollup-plugin-dts';export default [{//入口文件input: "./src/sdk/index.ts",output: [//打包esModule{file: path.resolve(__dirname, './sdk-dist/index.esm.js'),format: "es"},//打包common js{file: path.resolve(__dirname, './sdk-dist/index.cjs.js'),format: "cjs"},//打包 AMD CMD UMD{input: "./src/sdk/index.ts",file: path.resolve(__dirname, './sdk-dist/index.js'),format: "umd",name: "tracker"}],//配置tsplugins: [ts(),]
}, {//打包声明文件input: "./src/sdk/index.ts",output:{file: path.resolve(__dirname, './sdk-dist/index.d.ts'),format: "es",},plugins: [dts()]
}]

sdk/index.ts

export default class MySdk {public name: string;public version: string;public fn:()=>void;public constructor(options: any) {this.init(options)}private init(options: any): any {this.name = "my-sdk"this.version = "1.0.0"this.fn = ():void=>{console.log("hello sdk")}if(typeof options === 'object'){Object.keys(options).forEach((key:string)=>{this[key] = options[key]})}console.log("this",this)}}

创建好上面的 sdk.config.js 和 sdk/index.ts  文件 后

就可以打包 sdk 包了

pro.config.js

import ts from 'rollup-plugin-typescript2'
import path from 'path'
import dts from 'rollup-plugin-dts';
import commonjs from '@rollup/plugin-commonjs'export default [{//入口文件input: "./src/pro/index.ts",output: [//打包esModule{file: path.resolve(__dirname, './dist/index.esm.js'),format: "es"},//打包common js{file: path.resolve(__dirname, './dist/index.cjs.js'),format: "cjs"},//打包 AMD CMD UMD{input: "./src/pro/index.ts",file: path.resolve(__dirname, './dist/index.js'),format: "umd",name: "tracker"}],//配置tsplugins: [commonjs(),ts(),]
}, {//打包声明文件input: "./src/pro/index.ts",output:{file: path.resolve(__dirname, './dist/index.d.ts'),format: "es",},plugins: [dts()]
}]

/pro/index.ts

import sdk from '../../sdk-dist/index'const MySdk = new sdk({url:"127.0.0.1"
})MySdk.fn&&MySdk.fn()

在 /pro/index.ts 上使用我们前面打好的sdk包

index.html



ivanfor666'sdk


(使用vscode的小伙棒)最后使用 Live Server 插件, 直接以静态服务器形式运行打开 index.html

成功使用sdk。

end!!!

有代码疑问可以直接下载下面源码查阅。

如果学习后对你有帮助,请点个赞,让更多小伙棒得到帮助吧!

源码:

 ivanfor666 / 前端初学

相关内容