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
https://github.com/jlooper/angular-starter
Goal:
- 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
Pro:
- easy to start a project
Contra:
- 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”
2. npm-package
Goal:
- 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
Pro:
- useful if your web app is already finished
- projects can be placed in different folders
Contra:
- you need a build system and a private npm repository
3. shared-folder
Goal:
- web app client: put all shared angular code into a “shared” folder
- include the “shared” folder via symlinks into your NativeScript app/ folder
Pro:
- nice for prototyping
- pragmatic
- every project can use the own build tool
Contra:
- not sure, if it works under Windows
- Angular versions and other dependencies always have to be the same in both projects
Hints
- 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
Conclusion
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.