Adding types to your Vite library build: a step-by-step guide
P粉426780515
P粉426780515 2024-01-21 15:57:45
0
2
585

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粉426780515
P粉426780515

reply all(2)
P粉466643318

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

vue-tsc --declaration --emitDeclarationOnly

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

P粉386318086

You can use vite-plugin-dts

import dts from "vite-plugin-dts";

export default defineConfig({
  plugins: [
    dts({
      insertTypesEntry: true,
    }),
  ],
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!