系列索引
前言
埋点就是数据采集/数据处理/数据分析和挖掘, 如用户停留时间,点击按钮等。
TS: 强类型javascript,适合中大型项目,减少开发阶段不必要的错误,方便维护和测试
Rollup: 相比webpack轻量,打包产物可读性强,适合开发SDK和一些框架,webpack适合项目。
环境搭建
目录结构
SDK
src
core 核心代码
utils 工具函数
types 声明文件
rollup.config.js
tsconfig.json
package.json
- 手动创建src目录下对应目录及index.ts文件及rollup.config.js文件
- 执行
pnpm init生成package.json文件 - 执行
node_modules/.bin/tsc --init生成tsconfig.json文件
依赖安装
# 打包工具
pnpm i --dev rollup
# typescrpit基础库(IDE识别.ts解析文件支持)
pnpm i --dev typescript
# typescript 解析编译库
pnpm i --dev rollup-plugin-typescript2
# .d.ts生成工具
pnpm i -D rollup-plugin-dts
配置rollup
配置rollup.cofing.js
import path from 'path'
import ts from 'rollup-plugin-typescript2'
import dts from 'rollup-plugin-dts'
// https://rollupjs.org/guide/en/#configuration-files
export default [
{
input: './src/core/index.ts',
output: [
{
file: path.resolve(__dirname, './dist/index.esm.js'),
format: 'es'
},
{
file: path.resolve(__dirname, './dist/index.cjs.js'),
format: 'cjs'
},
{
file: path.resolve(__dirname, './dist/index.js'),
format: 'umd',
name: 'trackingSdk'
}
],
plugins: [
ts()
]
},
{
input: './src/core/index.ts',
output: [
{
file: path.resolve(__dirname, './dist/index.d.ts'),
format: 'es'
}
],
plugins: [
dts()
]
}
]
配置package.json
// scripts 配置 新增
"build": "rollup -c"
执行 pnpm run build. 报错如下:
> rollup -c
./src/core/index.ts → dist/index.esm.js, dist/index.cjs.js, dist/index.js...
[!] Error: Incompatible tsconfig option. Module resolves to 'CommonJS'. This is incompatible with rollup, please use 'module: "ES2015"' or 'module: "ESNext"'.
Error: Incompatible tsconfig option. Module resolves to 'CommonJS'. This is incompatible with rollup, please use 'module: "ES2015"' or 'module: "ESNext"'.
以上报错意思是rollup在解析ts文件为commonJS与tsconfig中的module(默认是commonjs)不兼容,这里我们修改为ESNext
执行build
执行pnpm run build, 可以看到,dist目录下有生成的文件如下:
- index.cjs.js // commonjs格式
- index.d.ts // 类型声明文件
- index.esm.js // es 格式
- index.js // umd格式