Vue.js で作ったページを Parcel でビルドして NW.js でデスクトップアプリ化してみた


はじめに

NW.js を使うと web 技術を利用してデスクトップアプリを作ることが出来ます。今回は以下の技術の組み合わせでシンプルなデスクトップアプリを作っていました。

  • Vue.js
  • TypeScript
  • Parcel
  • NW.js

まずはプロジェクトを作る

新しく空のディレクトリを作り、その中で npm init を実行して package.json を作ります。

$ npm init -y

parcel-bundler をインストールします。

$ npm i -D parcel-bundler

Vue.js でアプリを作る

まずは index.html を作ります。

<html>
<body>
  <div id="app"></div>
  <script src="./main.ts"></script>
</body>
</html>

次に main.ts を追加します。

import Vue from "vue";
import App from "./App.vue";

new Vue({
  el: "#app",
  render: h => h(App)
});

そして App.vue を追加します。

<template>
  <section>
    <p>{{count}}</p>
    <button @click="addCount(1)">UP</button>
    <button @click="addCount(-1)">DOWN</button>
  </section>
</template>

<script lang="ts">
export default {
  data () {
    return { count: 0 };
  },
  methods: {
    addCount(amount: number): void {
      this.count += amount;
    }
  }
};
</script>

ビルドする

package.jsonscriptstart コマンドを追加します。

  "scripts": {
    "start": "parcel index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

NW.js 起動時に正しく読み込めるように --public-url ./ を追加しています。

一度 npm start を実行して依存するパッケージをインストールします。

ここまでの内容は以下の記事と全く同じです。

NW.js で動かす

まずは npm コマンドで nw コマンドをインストールします。

$ npm i -S nw

package.jsonmainbuild/index.html にします。

  "main": "build/index.html",

package.jsonscript を次のようにします。

  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --out-dir ./build --public-url ./",
    "nw": "nw",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

npm run build で html と js にコンパイルします。

$ npm run build

npm run nw で NW.js でアプリを実行します。

$ npm run nw

実行すると以下のようなウインドウが表示されます。

package.json 全体は最終的に以下のようになりました。

{
  "name": "vue-nwjs",
  "version": "1.0.0",
  "description": "",
  "main": "build/index.html",
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --out-dir ./build --public-url ./",
    "nw": "nw",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@vue/component-compiler-utils": "^2.1.0",
    "parcel-bundler": "^1.9.7",
    "typescript": "^3.0.1",
    "vue-template-compiler": "^2.5.17"
  },
  "dependencies": {
    "nw": "^0.32.1",
    "vue": "^2.5.17",
    "vue-hot-reload-api": "^2.3.0"
  }
}

まとめ

一通り NW.js を使ってデスクトップアプリを作れそうな気がしてきたので、次はもう少し複雑なアプリを作ってみたいと思います。