search

Home  >  Q&A  >  body text

Adding types to your Vite library build: a step-by-step guide

I used the library pattern as per the vite documentation and was able to generate a working component library.

I created the project using vue-ts preset and defined the props and their types in my component and used some interfaces. But when I build the library, no types are included.

How to add types to the final build, whether automatically inferred from components or manually using definition files?

More Information Here is more information about my file:

tsconfig.json

{
  "name": "@mneelansh/test-lib",
  "private": false,
  "version": "0.0.2",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "emitDeclarationOnly": true, // testing
  "declaration": true, // testing
  "main": "./dist/lib.umd.js",
  "module": "./dist/lib.es.js",
  "types": "./dist/main.d.ts",
  "exports": {
    ".": {
      "import": "./dist/lib.es.js",
      "require": "./dist/lib.umd.js"
    },
    "./dist/style.css": "./dist/style.css"
  },
  "files": [
    "dist"
  ],
  "dependencies": {
    "@types/node": "^17.0.25",
    "vue": "^3.2.25"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.1",
    "typescript": "^4.5.4",
    "vite": "^2.9.5",
    "vue-tsc": "^0.34.7"
  }
}

I added emitDeclarationOnly and declaration attributes but that didn't help.

Myvite.config.ts:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

const path = require("path");

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/index.ts"),
      name: "Button",
      fileName: (format) => `lib.${format}.js`,
    },
    rollupOptions: {
      external: ["vue"],
      output: {
        globals: {
          vue: "Vue",
        },
      },
    },
  },
  plugins: [vue()],
});


P粉426780515P粉426780515303 days ago621

reply all(2)I'll reply

  • P粉466643318

    P粉4666433182024-01-22 12:15:19

    I personally think a better way is to use vue-tsc:

    vue-tsc --declaration --emitDeclarationOnly

    Please refer to https://stackoverflow.com/a/70343443/398287

    reply
    0
  • P粉386318086

    P粉3863180862024-01-22 10:17:41

    You can use vite-plugin-dts

    import dts from "vite-plugin-dts";
    
    export default defineConfig({
      plugins: [
        dts({
          insertTypesEntry: true,
        }),
      ],
    

    reply
    0
  • Cancelreply