实现一个函数去监听dom宽高的变化,并且发布NPM包,然后使用到项目中
步骤
1.5W3H 八何分析法
2.如何监听dom宽高变化
3.如何用vite 打包库
4.如何发布npm
一、NPM包新建过程
查看完整目录
1.生成 package.json
npm init
生成TS配置文件 tsconfig.json
npm install typescript npx tsc --init
新建vite.config.ts
import { defineConfig } from 'vite'
//globals umd 支持 amd cmd cjs 全局变量模式export default defineConfig({build: {lib: {// Could also be a dictionary or array of multiple entry pointsentry: 'src/index.ts',name: 'useResize',// the proper extensions will be added// fileName: 'my-lib',},rollupOptions: {// 确保外部化处理那些你不想打包进库的依赖external: ['vue'],output: {// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量globals: {useResize: 'useResize',},},},},
})
写功能src/index.ts
import { App, defineComponent, onMounted } from 'vue'function useResize(el: HTMLElement, callback: (cr: DOMRectReadOnly,resize:ResizeObserver) => void) {let resize: ResizeObserverresize = new ResizeObserver((entries) => {for (let entry of entries) {const cr = entry.contentRect;callback(cr,resize)}});resize.observe(el)
}const install = (app: App) => {app.directive('resize', {mounted(el, binding) {useResize(el, binding.value)}})
}useResize.install = installexport default useResize
新建index.d.ts 编写声明文件
// 声明文件
declare const useResize: {(el: HTMLElement, callback: Function): void;install: (app: App) => void;
};export default useResize
装进依赖里面devDependencies npm i vite -D 装进依赖里面devDependencies
npm i vue -D
编写配置
最后 打包,package.json 添加配置 require import 查找
npm run build
"main": "dist/v-resize-tc.umd.js",
"module": "dist/v-resize-tc.mjs",
配置哪些文件需要发布到npm
"files": [ "dist", "index.d.ts" ],
配置版本号,每次发布需要修改
"version": "0.0.1",
package.json完整代码
{"name": "v-resize-tc","version": "0.0.2","description": "实现一个函数同时支持 hook 和 自定义指令 去监听dom宽高的变化","main": "dist/v-resize-tc.umd.js","module": "dist/v-resize-tc.mjs","scripts": {"test": "echo \"Error: no test specified\" && exit 1","build": "vite build"},"author": "tangce","files": ["dist","index.d.ts"],"license": "ISC","dependencies": {"typescript": "^5.1.6"},"devDependencies": {"vite": "^4.4.4","vue": "^3.3.4"}
}
.npmignore忽略发布
# .npmignore
/node_modules
/src
二、发布NPM
1.注册账号
npm adduser
2.登录账号
npm login
3.打包
npm run build
4.输入 发布NPM
npm publish
常见错误情况处理-403,地址切换问题
通过安装nrm依赖包,管理和切换镜像地址:
npm install -g nrm
安装后,输入以下指令,切换到官方源地址
nrm use npm
发布完成后,再切换回淘宝镜像地址
nrm use taobao
查看当前地址
npm get registry
查看当前用户名
npm whoam i
附上代码及截图
三、项目中使用包
引入包
npm i v-resize-tc -D
具体使用情况
<template><a href="https://www.npmjs.com/package/v-resize-tc">https://www.npmjs.com/package/v-resize-tc</a><div class="resizeBox">https://www.npmjs.com/package/v-resize-tc</div>
</template>
<script setup lang='ts'>
import useResize from 'v-resize-tc'
import { onMounted } from 'vue'
onMounted(() => {useResize(document.querySelector('.resizeBox') as HTMLElement, (e:any) => {console.log(e)})
})
</script>
<style scoped lang='scss'>
.resizeBox{width: 300px;height: 300px;border: 1px solid #ccc;resize: both;overflow: hidden;
}
</style>