问vue3如何封装组件库和指令并上传到npm?

497 阅读1分钟
  • 摘要

日常开发项目的过程中为了避免重复编写代码可能需要封装一些组件和指令,不同的项目之间如果不嫌麻烦的话可以直接手动copy,但每次组件更新的时候修复bug的时候项目一多,就比较痛恨了,所以为了避免这种copy的事情我们一般上传到npm库进行集中管理。

  • 教程

    • 1、在项目中编写components文件夹下面编写组件。
    • 2、在components文件夹下面建一个index.ts文件用于注册组件和指令看下面的index.ts文件的代码。
    • 3、新建一个指令的文件夹命名自己随便命名我的叫directives
    • 5、一切准备好了之后需要配置打包,我用的是vite
    • 6、打包完成之后需要配置你的package.json文件
    • 7、配置完了之后需要登录你npm使用命名npm login npm publish
    • 4、废话不多说上图片
    • 组件和指令的文件

image-20220816172645297.png

-   组件中index.ts文件代码

    ```
    import { App, Directive } from 'vue'
    import Button from './button/index.vue'
    import * as directives from '@/directives/index'
    export type DirectiveType = { [key: string]: Directive }
    const components = [
      Button
    ]
    const install: any = function (app: App) {
        // 防止已经注册过的组件重复注册
      if (install.installed) return
      install.installed = true
      components.forEach(res => {
        app.component(res.name, res)
      })
        // 注册指令
      Object.keys(directives).forEach(res => {
        app.directive(res, (directives as DirectiveType)[res])
      })
    }
    // 导出一个install的函数或者一个对象里面有一个install的方法
    export default {
      install
    }
    ```

    -   `package.json` 配置

image-20220816175641557.png - vite.config.ts 的配置

image-20220816180026348.png

    -   最后登录你的npm使用`npm pulbish` 上传到npm服务器上
  • 总结

    世上无难事,只要肯放弃。

    加油你还年轻。

\