javascript - Hur lägger jag till typer till en Vite-biblioteksbyggnad?
Jag följde Vite-dokumentationen för att använda biblioteksläge och jag kan producera ett fungerande komponentbibliotek.
Jag skapade projektet med vue-ts-förinställningen och i min komponent har jag definierat props med deras typer och använt några gränssnitt. Men när jag bygger biblioteket inkluderas inga typer.
Hur lägger jag till typer för den slutgiltiga byggnaden, antingen härledda automatiskt från komponenter eller manuellt med definitionsfiler?
Mer information Här är lite mer information om mina filer:
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"
}
}
Jag lade till emitDeclarationOnly och declaration-egenskaperna men det hjälpte inte.
Min vite.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()],
});
Svar #1
Du kan använda vite-plugin-dts
import dts from "vite-plugin-dts";
export default defineConfig({
plugins: [
dts({
insertTypesEntry: true,
}),
],
Svar #2
Vanligtvis med vite- och typescript-projekt behöver du lägga till typkontroll innan bygg, eftersom vite inte gör det själv. Här använder jag också vite-plugin-dts som i inlägget från Julien Kode, och för typkontroll rollup-plugin-typescript2.
Slutligen min vite.config.js:
import { defineConfig } from 'vite';
import Vue from '@vitejs/plugin-vue2';
import dts from 'vite-plugin-dts';
import rollupTs from 'rollup-plugin-typescript2';
export default defineConfig({
plugins: [
Vue(),
dts({ insertTypesEntry: true }),
// only for type checking
{
...rollupTs({
check: true,
tsconfig: './tsconfig.json',
tsconfigOverride: {
noEmits: true,
},
}),
// run before build
enforce: 'pre',
},
],
build: {
sourcemap: true,
lib: {
entry: './src/index.ts',
fileName: 'index',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: [
'vue',
'vue-class-component',
'vue-property-decorator',
'vuex',
'vuex-class',
],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
});
