31
loading...
This website collects cookies to deliver better user experience
<script setup>
syntax.<script setup lang="ts">
import { reactive } from "vue";
interface Props {
primary?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
primary: false,
});
const { primary } = reactive(props);
</script>
<template>
<button class="btn" :class="{ primary }">
<slot />
</button>
</template>
<style scoped>
.btn {
padding: 0.5rem 1rem;
}
.btn.primary {
background: hsl(239, 100%, 27%);
color: #fff;
}
</style>
// src/index.ts
export { default as MyButton } from "./MyButton";
vite.config.ts
(or .js
).// vite.config.ts
const path = require("path");
const { defineConfig } = require("vite");
module.exports = defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, "src/index.ts"),
name: "MyComponentLib",
fileName: (format) => `my-component-lib.${format}.js`,
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ["vue"],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: "Vue",
},
},
},
},
});
npm run build
you should get the output in the dist
folder.If you're getting an error regarding __dirname
or path
you need to install node type declarations
npm i -D @types/node
package.json
to point at correct built files. We are defining the entry point to the library.// "my-component-lib" should match the "name" field in your package.json
{
"files": ["dist"],
"main": "./dist/my-component-lib.umd.js",
"module": "./dist/my-component-lib.es.js",
"exports": {
".": {
"import": "./dist/my-component-lib.es.js",
"require": "./dist/my-component-lib.umd.js"
}
}
}
name
field in your package.json
to your preferred library name.npm pack
package.json
. After running this add the following to the dependencies
field:"dependencies": {
"my-component-lib": "my-component-lib-0.0.0.tgz"
},
If you run into dependency errors try deleting the zipped file and packing it again, or deleting the package.lock.json
and node_modules
and runningnpm install
again.
<script setup lang="ts">
import { MyButton } from "my-component-lib";
import "/node_modules/my-component-lib/dist/style.css";
</script>
vue-tsc
package.Make sure to update vue-tsc
to a newer version since the create-vue
CLI defaults to an older version.
tsconfig.json
:{
"outDir": "dist",
"declaration": true
}
{
"build": "vite build && vue-tsc --emitDeclarationOnly && mv dist/src dist/types"
}
package.json
{
"types": "./dist/types/index.d.ts"
}
types
directory, by default they would be in a src
directory since that is our target inside the tsconfig
.If it's still there try deleting your node_modules
and package.lock.json
and installing the packages again.
npm login # authenticate
npm publish # publish