ワンソース、マルチプラットフォームは甘美な響きであり、誰もが夢見る存在です。ずっと昔から言われており、アプリ開発において最も望まれている存在かも知れません。 かつてはTitaniumが有力候補が出てきたのですが、最近ではあまり聞かれません。そこで登場したのがNativeScriptです。

NativeScriptの使い方

NativeScriptはCLIで操作します。node/Homebrew/mono/JDK/ant/Android SDKなどが必要です。準備が終わったら、

$ npm i -g nativescript

にてインストールができます。

コマンドは次のようになります。

// 対応プラットフォームを追加
tns platform add android
tns platform add ios

// デバイスで実行
tns run android
tns run ios

// シミュレータで実行
tns run android --emulator
tns run ios --emulator

タップも使えるアプリができました!

コードは次のようになります。Titaniumに比べるとより素のJavaScriptに近い?

var observable = require("data/observable");

var counter = 42;

var mainViewModel = new observable.Observable();
mainViewModel.set("message", counter + " taps left");
mainViewModel.tapAction = function () {
   counter--;
   if (counter < = 0) {
     mainViewModel.set("message", "Hoorraaay! You unlocked the NativeScript clicker achievement!");
   }
   else {
     mainViewModel.set("message", counter + " taps left");
   }
};
exports.mainViewModel = mainViewModel;

画面はXMLで定義します。

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
  <stacklayout>
    <label text="Tap the button" cssClass="title"/>
    <button text="TAP" tap="{{ tapAction }}" />
    <label text="{{ message }}" cssClass="message" textWrap="true"/>
  </stacklayout>

Titaniumとの違いとして、ネイティブのAPIに直接触れる点を挙げています。Titaniumの場合、ラッパーが必要でしたが、NativeScriptはそうではないようです。実行エンジンはJavaScriptであり、その点はTitaniumと同じです。

技術的にはJavaScriptとスタイルシートでアプリ作成ができるようになっています。対応プラットフォームはiOS/Android/Windows Phoneとなっています。

NativeScriptはWindows/Mac OSX/Linux用、Apache License 2.0のオープンソース・ソフトウェアです。

Cross-Platform Native Development with Javascript NativeScript