blog post cover image

Javascipt フルスタックフレームワークMeteor JSを触ってみた

投稿日付:10/1/2022
2

きっかけ

javascript(NodeJS)のバックエンド開発といえば、Express JSしか出てこないので、PHPのlaravelやPythonでのDjangoのようなフルスタックなフレームワークをないのかなとと調べた結果、日本語での情報が物凄い少ないですが、Githubでのスター数が40kも超えているMeteor JSがexpressの次に出てきたからからです。

フルスタックフレームワークとは

極端にいうと言葉の通りにフロントとバックエンドもカバーしたフレームワークのこと。 PHPだったら、Laravelが一番人気だと思いますが。いわゆるM(model)V(view)C(controller)フレームワークですね。

インストール

linux/macOSの場合

curl https://install.meteor.com/ | sh

windows10の場合 (windows7も対応しているとのこと)

パッケージ管理ツールChocolateyを使うことをお勧めされているみたいです。 Chocolateyがインストールしたら以下のコマンド叩けばいいみたいですね。 choco install meteor

*powerShellを管理者権限で起動してコマンド叩きます*

そうしたらダウンタウンが始まります。 最後のインストールの段階で少し時間がかかるみたいですが、もし止まったまま長い時間経ってもなんも反応しなかったら、7-Zipをインストールすれば大丈夫みたいです(gihub issueから)

インストール終わったら、新しくコマンドプロンプトを開いて、meteorと叩いてみましょう,以下のように表示されたら、インストール成功しているということです✨

run: You're not in a Meteor project directory.

To create a new Meteor project:
  meteor create <project name>
For example:
  meteor create myapp

For more help, see 'meteor --help'.

プロジェクトを作成

開発のディレクトリ作成し、meteor create simple-todosを叩きます。 ダウンロードが終わったら、simple-todosフォルダーのディレクトリ構造がこう↓なっているはずです。

client/main.js        # a JavaScript entry point loaded on the client
client/main.html      # an HTML file that defines view templates
client/main.css       # a CSS file to define your app's styles
server/main.js        # a JavaScript entry point loaded on the server
test/main.js          # a JavaScript entry point when running tests
package.json          # a control file for installing npm packages
package-lock.json     # describes the npm dependency tree
node_modules/         # packages installed by npm
.meteor/              # internal Meteor files
.gitignore            # a control file for git

ローカルで起動

以下のコマンドを実行↓

cd simple-todos meteor

ローカルでdevサーバーが3000ポートで起動します。

localserver

公式にはこう書いてありますが、今回は直接vueのセッテアップをしていきたいと思います

You can play around with this default app for a bit before we continue. For example, try editing the text in <h1> inside client/main.html using your favorite text editor. When you save the file, the page in your browser will automatically update with the new content. We call this hot code push.

vueのセッテアップ

ローカルサーバー起動したまま、別のコマンドプロンプトを開いて、meteor npmでvueをインストールします。 meteor npm install --save vue

meteor npm supports the same features as npm とのこと

次にakryum:vue-componentというパッケージが必要らしいです meteor add akryum:vue-component

We also need to add the akryum:vue-component Meteor package to allow us to create files with the .vue extension, which makes it possible to create Vue components in the single file format. とのこと

blaze-html-templates の代わりに static-htmlを上書きする

Meteorのblazeテンプレートがデフォルトなので、まずそれを削除します。 meteor remove blaze-html-templates を実行します。

static-htmlパッケージをインストールします。 meteor add static-htmlを実行します

さっき作成したデフォルトのコードを修正します

client/main.html

<head>
  <title>Todo List</title>
</head>

<body>
  <div id="app">
    <!-- ここにvue jsがレンダリングされる -->
  </div>
</body>

client/main.js


import { Meteor } from 'meteor/meteor';
import Vue from 'vue';

import App from '../imports/ui/App.vue';

Meteor.startup(() => {
  new Vue({
    el: '#app',
    ...App,
  });
});

次にルートディレクトリに新しくimports/uiのディレクトリを作成し、中にApp.vueファイルを作成します。

imports/ui/App.vue


<template>
  <div className="container">
    <header>
      <h1>Todo List</h1>
    </header>
    <ul>
      <Task
        v-for="task in getTasks()"
        v-bind:key="task._id"
        v-bind:task="task"
      />
    </ul>
  </div>
</template>

<script>
import Vue from "vue";
import Task from "./Task.vue";

export default {
  components: {
    Task
  },
  data() {
    return {};
  },
  methods: {
    getTasks() {
      return [
        { _id: 1, text: "This is task 1" },
        { _id: 2, text: "This is task 2" },
        { _id: 3, text: "This is task 3" }
      ];
    }
  }
};
</script>

次に同じディレクトリにTask.vueを作成します

imports/ui/Task.vue


<template>
  <li>{{ this.task.text }}</li>
</template>

<script>
export default {
  props: ["task"],
  data() {
    return {};
  }
};
</script>

ブラウザーで起動中のlocalhost:3000をそのままリロードします。

vue-setup-with-meteor

おー!、表示されました、ちょっと感動ですね😁

ちょっとしたcssを追加してみます

client/main.css


/* CSS declarations go here */
body {
  padding: 10px;
  font-family: sans-serif;
  background-color: #315481;
  background-image: linear-gradient(to bottom, #315481, #918e82 100%);
  background-attachment: fixed;

  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;

  padding: 0;
  margin: 0;

  font-size: 14px;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  min-height: 100%;
  background: white;
}

header {
  background: #d2edf4;
  background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
  padding: 20px 15px 15px 15px;
  position: relative;
}

#login-buttons {
  display: block;
}

h1 {
  font-size: 1.5em;
  margin: 0;
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 1em;
}

form {
  margin-top: 10px;
  margin-bottom: -10px;
  position: relative;
}

.new-task input {
  box-sizing: border-box;
  padding: 10px 0;
  background: transparent;
  border: none;
  width: 100%;
  padding-right: 80px;
  font-size: 1em;
}

.new-task input:focus {
  outline: 0;
}

ul {
  margin: 0;
  padding: 0;
  background: white;
}

.delete {
  float: right;
  font-weight: bold;
  background: none;
  font-size: 1em;
  border: none;
  position: relative;
}

li {
  position: relative;
  list-style: none;
  padding: 15px;
  border-bottom: #eee solid 1px;
}

li .text {
  margin-left: 10px;
}

li.checked {
  color: #888;
}

li.checked .text {
  text-decoration: line-through;
}

li.private {
  background: #eee;
  border-color: #ddd;
}

header .hide-completed {
  float: right;
}

.toggle-private {
  margin-left: 5px;
}

@media (max-width: 600px) {
  li {
    padding: 12px 15px;
  }

  .search {
    width: 150px;
    clear: both;
  }

  .new-task input {
    padding-bottom: 5px;
  }
}

added-css

ここからは自由にvuejsをかけるということですね、

REST APIを作ってみる

せっかくなので、rest apiを作ってみます。

importsフォルダーの中にapisというフォルダーを作成し、rest.jsを作成します。 コード書く前にパッケージをインストールします。 meteor add nimble:restivus インストール終わったら

imports/apis/rest.js


import { Restivus } from 'meteor/nimble:restivus';

export const Api = new Restivus({
  prettyJson: true,
});

Api.addRoute('hello', { 
  get: { 
    action: function() { 
      return { 
        status: 'success', 
        data: { 
          message: 'Hello, REST API!', 
        }, 
      }; 
    }, 
  },
});

export default Api;

server/main.jsにインポートして上げます


import { Meteor } from 'meteor/meteor';

import "../imports/api/rest" //ここの行追加

Meteor.startup(() => {
  // code to run on server at startup
});

新しいコマンドプロンプトを開いて、APIをテストしてみます。

D:meteor\simple-todos>curl http://localhost:3000/api/hello
{
  "status": "success",
  "data": {
    "message": "Hello, REST API!"
  }
}

ちゃんと帰ってきてますね。

感想

Webpackやbableの設定もせずにVueJSが動いてしまっているのが凄いと思いました。