You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js组件库创建遇阻:组件导出与引用失败求指导

Vue组件库构建问题与解决方案

动机

创建包含按钮、头部等组件的Vue.js组件库,用于多项目复用,保证不同项目样式统一。

无效尝试方案

计划采用以下文件结构实现组件库:

  • /src/components/TestComponent.vue - Vue单文件组件(SFC)
  • /src/main.js
  • /src/package.js

各文件代码如下:

TestComponent.vue

<template>
  <div class="test-component">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'test-component',
  props: {
    msg: String
  }
}
</script>

<style scoped>

</style>

/src/main.js(组件导出)

import testComponent from './components/TestComponent.vue'

export { testComponent }

package.json构建脚本

{   
    "name": "@my/test-lib",
    "scripts": {
      "build": "vue-cli-service build --target lib --name test-lib src/main.js",
...
}

执行npm run build构建、npm publish发布到私有仓库后,在其他项目中按规范引用时,报错Cannot find module '@my/test-lib',怀疑导出方式存在问题。

可行但有局限的方案

保持TestComponent.vue代码不变,修改main.js使用@vue/web-component-wrapper:

import Vue from "vue";
import wrap from "@vue/web-component-wrapper";

import testComponent from "./components/TestComponent.vue";
const wrappedTestComponent = wrap(Vue, testComponent);
window.customElements.define("test-component", wrappedTestComponent);

该方案的局限:仅支持String类型的props,无法原生传递对象(排除序列化/反序列化这类脆弱方案)。


内容的提问来源于stack exchange,提问作者noha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:15:33