June 12, 2017
Reuse Angular Code within NativeScript Apps
NativeScript is a great framework to write mobile Apps for Android and iOS with Angular (2, 4 and so on).
Read on, if you:
- have an existing Angular Web App or are planning to develop one
- you want to offer a native App for Android and iOS without a lot of extra work
TL;DR It is possible to reuse code, especially Services and Pipes, if you are lucky some of the Components.
I will show three possibilities to share code between a web and a native app, but in regards to usability keep following in mind:
- a website has more static content and more space to show elements
- a smartphone has a smaller screen, users are used to the native elements and want to find/use stuff inside apps fast without much distraction
So maybe it is not the best practice to port a web app 1:1 on a native app.
But now, the three possibilities …
1. Seed Projects
- a single workspace with a working Angular Web App and NativeScript App
- maximum code reuse, at first only templates are platform dependent
- Angular: *.html
- NativeScript: *.tns.html
- shared code in “shared” folder
- own build system
- easy to start a project
- mobile and web UIs are different, so at a long run, you are going to need components for each platform and can only share services and pipes
- lot’s of build “magic”
- pack your shared code into a npm package
- shared Angular should be placed in Angular modules
- use the package and the modules in your NativeScript app
- useful if your web app is already finished
- projects can be placed in different folders
- you need a build system and a private npm repository
- web app client: put all shared angular code into a “shared” folder
- include the “shared” folder via symlinks into your NativeScript app/ folder
- nice for prototyping
- every project can use the own build tool
- not sure, if it works under Windows
- Angular versions and other dependencies always have to be the same in both projects
- don’t reference window in shared code
- abstract platform specific code with e.g. facade pattern (there is no local-storage on a mobile app)
- use the same npm dependencies
I used the last approach to write a prototype NativeScript app from an existing web-app (Calendar for Trello). I was able to reuse the a complete redux store and all of the services, after I matched the dependencies on both projects.
I didn’t reuse any of the components, because in my opinion the mobile app had a different use case. It worked quite well and showed us, that it’s possible to reuse code and get a native UI with NativeScript.