Mobile, NativeScript, TypeScript, Vue.js • December 14th, 2018
Over the past year or so I have been working on a project that uses Vue.js for the web UI. I’ve really grown to love the framework over that time and found myself wishing I could use it for native mobile apps.
This article assumes that you have installed the NativeScript CLI and mobile SDKs. If you haven’t, you can follow this guide. It is for NativeScript 5.0 and NativeScript-Vue 2.0.
Create the Project
The first thing I’m going to cover is setting up the project from the CLI. It’s pretty simple. Just type
at the command line. You’ll be presented with the following:
Choose Vue.js and the initial project will be configured for you.
cd into your project directory and open it in VS Code (or your preferred IDE 🤷♂️)
Configuring for TypeScript
To transpile our Vue TS components we need the TypeScript Loader for Webpack and TypeScript installed. The project setup should have already installed the TS Loader, but I’ll include it here anyway. We also need Vue Property Decorator to add component and property annotations. Finally we need the full Vue.js package, but only for type definitions and autocomplete.
These are installed by running:
Webpack has to be configured to route .ts and .vue files through the TypeScript Loader. When I first used NS-Vue, I was using NS 4.x. I recently updated to 5.1 and had to manually add the TypeScript configuration to webpack.config.js. However, when creating a new NS-Vue project from scratch in version 5.x, these settings are already in place. I’ll highlight them here anyway in case anyone runs into the same issues as I did.
- Update the entryPath to have a .ts file extension.
- Add .ts to the extensions to resolve:
- Add an alias to map Vue import to the NativeScript-Vue library. This is so that type declarations and autocomplete will work correctly.
- Add a rule so that .ts and .vue files are procesed by the ts-loader.
We need to add tsconfig.json to the project root to set the TypeScript compiler options. The content below should work for any project. Note that we need to enable the experimentalDecorators setting so that we can add component decorators.
We now need to rename /app/app.js to app.ts so that it will be processed as a TypeScript file. You may see a compiler error where the module ‘./components/Home’ can’t be found. I haven’t fount a way to fix this, so I add a ts-ignore comment.
Open /app/components/Home.vue. Modify the script block so that the lang attribute is set to ts.