|
| 1 | +--- |
| 2 | +title: Using Typescript in Nativescript-Vue Apps |
| 3 | +authors: [championswimmer] |
| 4 | +toc: true |
| 5 | +intro: Many people love to build Vue apps with TypeScript. You can do that in NativeScript-Vue too. |
| 6 | +--- |
| 7 | + |
| 8 | +NativeScript-Vue uses a modified build of vue. The `nativescript-vue` package **is** that build. |
| 9 | +For TypeScript we need type definitions from Vue, so we need to install the original Vue package. |
| 10 | + |
| 11 | +```shell |
| 12 | +$ npm install --save-dev vue |
| 13 | +``` |
| 14 | + |
| 15 | +Once this is done, we have a problem. Anywhere in our code, if we write |
| 16 | + |
| 17 | +```js |
| 18 | +require('vue') |
| 19 | +``` |
| 20 | + |
| 21 | +or |
| 22 | + |
| 23 | +```ts |
| 24 | +import Vue from 'vue' |
| 25 | +``` |
| 26 | + |
| 27 | +it will be a huge problem, as we **do not ever** want to _actually_ use the original vue package. |
| 28 | +We just want to have it here for type definitions and autocomplete. |
| 29 | + |
| 30 | +Webpack comes to the rescue. We will add this to our webpack config, so that all `vue` imports |
| 31 | +are resolved to `nativescript-vue`: |
| 32 | + |
| 33 | +```js |
| 34 | +alias: { 'vue$': 'nativescript-vue' } |
| 35 | +``` |
| 36 | + |
| 37 | +**Use Typescript** |
| 38 | + |
| 39 | +This should set up up with Typescript already. Simply rename .js files to .ts or, if using SFC, then |
| 40 | + |
| 41 | +```vue |
| 42 | +<template> |
| 43 | + <!-- ... --> |
| 44 | +</template> |
| 45 | +
|
| 46 | +<script lang="ts"> |
| 47 | + // typescript code here |
| 48 | +</script> |
| 49 | +``` |
| 50 | + |
| 51 | +**Use Class-style components** |
| 52 | + |
| 53 | +You can now install vue-class-components |
| 54 | + |
| 55 | +```shell |
| 56 | +$ npm install --save-dev vue-class-components |
| 57 | +``` |
| 58 | + |
| 59 | +And write class-styled component code |
| 60 | + |
| 61 | +```ts |
| 62 | +import {Component} from 'vue-property-decorator' |
| 63 | + |
| 64 | +@Component |
| 65 | +export default class MyComponent extends Vue { |
| 66 | + count = 1 |
| 67 | + increment () { this.count++ } |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +That's it! You have TypeScript working in NativeScript-Vue! |
0 commit comments