如何将本地组件库上传到npm上

如何把本地开发的组件发布到npm上面,我们需要去了解vue封装组件的原理,利用vue.use(plugin)这个api, 我们需要把封装好的组件打包成vue库,并提供install方法发布到npm上去,Vue.use(plugin)自动执行插件中的install方法。

我们在这里主要介绍的是怎么把已经开发好的公共组件打包发布到npm上面。首先需要我们调整下目录结构 ----> 创建打包组件的文件 ----> 把打包文件发布到npm上

目录结构

  1. 在当前项目创建一个打包文件夹packages
  2. 将每个组件的文件调整下,每个组件下定义src/index (组件内容) 以及与src同级index目录(暴露当前组件)
javascript 复制代码
import { App } from 'vue'
import calendar from './src/index.vue'

// 让这个组件可以通过use的形式使用
export default {
  install(app: App) {
    app.component('jsq-calendar', calendar)
  }
}
  1. 在文件下packages创建index.js文件
javascript 复制代码
import { App } from 'vue'
import chooseArea from './chooseArea'
import chooseIcon from './chooseIcon'
import trend from './trend'
......

const components = [
    chooseArea,
    chooseIcon,
    trend,
    ......
]
export default {
    install(app: App) {
        components.map(item => {
            app.use(item)
        })
    }
}

创建打包命令

  1. 创建build.js用来打包组件
javascript 复制代码
const path = require('path')
const { defineConfig, build } = require('vite')
const vue = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')
const fxExtra = require('fs-extra')
const fs = require('fs')

// 打包入口文件夹
const entryDir = path.resolve(__dirname, '../packages')
// 出口文件夹
const outDir = path.resolve(__dirname, '../lib')

// vite基础配置
const baseConfig = defineConfig({
    configFile: false,
    publicDir: false,
    plugins: [vue(), vueJsx()]
})

// rollup配置
const rollupOptions = {
    external: ['vue', 'vue-router'],
    output: {
        globals: {
            vue: 'Vue'
        }
    }
}

// 全量打包构建
const buildAll = async () => {
    await build({
        ...baseConfig,
        build: {
            rollupOptions,
            lib: {
                entry: path.resolve(entryDir, 'index.ts'),
                name: 'jsq-element-components',
                fileName: 'jsq-element-components',
                formats: ['es', 'umd']
            },
            outDir
        }
    })
}

// 单组件打包构建
// name组件名称
const buildSingle = async (name) => {
    await build({
        ...baseConfig,
        build: {
            rollupOptions,
            lib: {
                entry: path.resolve(entryDir, name),
                name: 'index',
                fileName: 'index',
                formats: ['es', 'umd']
            },
            outDir: path.resolve(outDir, name)
        }
    })
}

// 每个组件生产package.json
const createPackageJson = (name) => {
    const fileStr = `
      {
        "name": "${name}",
        "main": "index.umd.js",
        "module": "index.es.js",
        "style": "style.css"
      }
    `
    // 输出
    fxExtra.outputFile(
        path.resolve(outDir, `${name}/package.json`),
        fileStr,
        'utf-8'
    )
}

// 打包成库
const buildLib = async () => {
    await buildAll()

    // 获取组件名称组成的数组
    const components = fs.readdirSync(entryDir).filter(name => {
        const componentDir = path.resolve(entryDir, name)
        const isDir = fs.lstatSync(componentDir).isDirectory()
        return isDir && fs.readdirSync(componentDir).includes('index.ts')
    })

    // 循环构建
    for(const name of components) {
        await buildSingle(name)
        createPackageJson(name)
    }
}
buildLib()
  1. 在package.json创建打包组件命令:"lib": "node ./build.js"
  2. 执行命令 npm run lib
  3. 在项目文件下会生产lib文件夹,这个就是发布到npm上的文件代码
  4. lib文件下执行 npm init -y 生产package.json文件
javascript 复制代码
{
    "name": "jsq-element-components", // 组件名称
    "version": "1.0.0", // 版本号
    "main": "index.umd.js",
    "module": "index.mjs",
    "types": "index.d.ts",
    "author": {
        "name": "jsq"
    },
    "keywords": [
        "ts",
        "封装组件",
        "vue-componets"
    ]
}

npm官网注册

  1. npm官网
  2. 注册账号

代码发布到npm上

  1. cd 到当前lib文件下
javascript 复制代码
cd lib 
  1. 先查看 npm 的 registry
javascript 复制代码
npm config get registry
  1. 设置 npm 的 registry 为官方源
javascript 复制代码
npm config set registry https://registry.npmjs.org
  1. 执行命令 npm login 登录到 npm
javascript 复制代码
npm login
  1. 执行命令 npm publish 发布到 npm
javascript 复制代码
npm publish
  1. 登录npm官网 点击packages 查看上传的代码

项目使用

  1. npm install 项目文件名称
javascript 复制代码
npm install jsq-element-components
  1. 在项目入口文件引入组件
javascript 复制代码
import App from './App.vue'	
// 组件
import jsqUI from 'jsq-element-components'
// 组件样式
import 'jsq-element-components/style.css'

const app = createApp(App)
app.use(jsqUI)
相关推荐
天平4 小时前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
原则猫5 小时前
前端基础大厦
前端
陈随易6 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart7 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒9 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰9 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
山河木马10 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林81810 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花10 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu122711 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude