Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue library typings

I'm making a Vue library as an NPM package which is intented to be used by other projects.

The entry point is main.ts, which exposes a plugin and some functions that I commonly use. A simplified example of main.ts:

import Vue from 'vue'
import Button from '@/components/button.vue'

const myPlugin = {
  install (vue: typeof Vue): void {
    vue.component('the-button', Button)
  }
}

function someFunction(a: number, b: number) {
  return a + b
}

export { myPlugin, someFunction }

I build the project using vue-cli-service build --target lib --name myLibrary src/main.ts.

Now to my question; how to specify and/or generate typings correctly? As far as I can see, there are two options:

  1. Set "typings": "src/main.ts" in my package.json and use the .ts files themselves as type references. Seems to work but I haven't seen any examples of this being used so I assume it's bad practice?

  2. Set "declaration": true and "outDir": "types" in my .tsconfig.json. Along with some tweaking in vue.config.js typings seems to be generated correctly, which I would specify with "typings": "types/main.d.ts" in the package.json file. Is this the preferred approach?

like image 386
Johan Avatar asked Apr 06 '20 19:04

Johan


People also ask

How do I add TS to Vue?

To let Typescript enters into your Vue components, 2 additions are mandatory in each component file: Adding the lang="ts" attribute to the script tag so that Typescript can recognized it.

Can I use TypeScript with Vue?

Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.

How do you define props in Vue composition API?

You define a prop named disabled in MyComponent. vue . ... and then add the component like this, passing in disabled . Note that :disabled="true" and just disabled mean the same thing in both cases - when props are defined or not.

What is Vue option API?

We use Options API in a Vue application to write and define different components. With this API, we can use options such as data , methods , and mounted . To state it simply, Options API is an old way to structure a Vue. JS application.


1 Answers

I would use the second approach, or better, for my packages I use the second approach.

For rotating-file-stream, which is not a Vue library, but a TypeScript package anyway, I'm using the said method, that let you to distribute (in the npm package) only the .js and the .d.ts files which makes the package a bit lighter. The original .ts files are always available on github for reference/documentation.

like image 165
Daniele Ricci Avatar answered Nov 14 '22 11:11

Daniele Ricci