Vue3封装自定义指令和hooks,并发布npm包
在Vue 3中,你可以创建自定义指令和hooks,并将它们打包成一个npm包的步骤如下:
- 创建自定义指令:
// directives/focus.js
export default {
mounted(el) {
el.focus();
}
};
- 创建hook:
// hooks/useFocus.js
import { ref, onMounted } from 'vue';
export default function() {
const isFocused = ref(false);
const focus = () => {
if (isFocused.value) {
document.activeElement.blur();
} else {
document.activeElement.focus();
}
isFocused.value = !isFocused.value;
};
onMounted(() => {
focus();
});
return { isFocused, focus };
}
- 创建插件入口文件:
// index.js
import FocusDirective from './directives/focus';
import useFocus from './hooks/useFocus';
const MyVuePackage = {
install(app) {
app.directive('focus', FocusDirective);
app.provide('useFocus', useFocus);
}
};
export default MyVuePackage;
- 配置
package.json
:
{
"name": "my-vue-package",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"vue": "^3.0.0"
},
"scripts": {
"build": "rollup -c"
},
"devDependencies": {
"rollup": "^2.30.0",
"rollup-plugin-vue": "^6.0.0",
"rollup-plugin-terser": "^7.0.0"
}
}
- 配置Rollup打包工具:
// rollup.config.js
import { defineConfig } from 'rollup';
import vue from 'rollup-plugin-vue';
import { terser } from 'rollup-plugin-terser';
export default defineConfig([
{
input: 'index.js',
output: [
{
file: 'dist/my-vue-package.cjs.js',
format: 'cjs'
},
{
file: 'dist/my-vue-package.esm.js',
format: 'es'
}
],
plugins: [vue(), terser()]
}
]);
发布npm包:
首先在本地打包你的插件:
npm run build
然后登录你的npm账号:
npm login
最后发布到npm:
npm publish
以上步骤会创建一个名为my-vue-package
的npm包,其中包含一个自定义指令v-focus
和一个hook useFocus
。你可以在Vue 3项目中通过npm安装并使用它们。
评论已关闭