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:
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?
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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With