How to create component library in vuejs

Viewed 23

Motivation

Create vuejs library with components (buttons, headers,...) for re-using it in more projects so they looks the same in different projects.

My not working idea

I would like to reach something like this:

When you have these files

  • /src/components/TestComponent.vue - vue SFC
  • /src/main.js
  • /src/package.js

Where:

  • 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 export that component:
import testComponent from './components/TestComponent.vue'

export { testComponent }
  • packake.json contains build description which should create library:
{   
    "name": "@my/test-lib",
    "scripts": {
      "build": "vue-cli-service build --target lib --name test-lib src/main.js",
...

So I can build it via npm run build and afterwards npm publish to private repo and afterwards use component TestComponent in another project like this:

<template>
    <div>
        <test-component msg="TEST"></test-component>
    </div>
</template>
<script>
import { testComponent } from "@my/test-lib"

export default {
    name: "usage-test",
    components: {
        testComponent
    }
};
</script>

<style scoped>
</style>

---> Except it doesnt work. It fails on Cannot find module '@my/test-lib'. My guess is that I am doing export somehow wrong. Can someone provide a hint?

Working idea

  • TestComponent.vue looks exactly the same as above

  • main.js use @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);

But this solution has a limitation. When usage - it accepts only String props. So no Objects by nature (I am not counting ser / deser brittle solution)

0 Answers
Related