Web系エンジニアのアウトプット練習場

エンジニアリングと書評が中心。たまに全然関係無い話もします。
トップページ/Firebase/Firebase + Vue.jsでなんかサービスを作成する忘備録 その1/
2018年07月19日

Firebase + Vue.jsでなんかサービスを作成する忘備録 その1

FirebaseVue.jsCircleCI

Firebaseへの登録

Googleアカウントがあれば、Firebaseのサービスを使用することが可能です。 Googleアカウントを作成・ログインした後、以下のリンクから「使ってみる」
https://console.firebase.google.com
へ接続します。

プロジェクトの作成

登録後の画面から「プロジェクトの作成」を選択します。

Firebaseのプロジェクト選択画面

プロジェクトIDは世界でユニークな文字列です。
既に同名のプロジェクトがある場合は「プロジェクト名-xxxxx」というような形でsuffixが付加されます。

Firebaseのプロジェクト作成画面

CLIのセットアップ

$ npm install -g firebase-tools
WARN notice [SECURITY] superstatic has the following vulnerability: 1 high. Go here for more details: https://nodesecurity.io/advisories?search=superstatic&version=5.0.2 - Run `npm i npm@latest -g` to upgrade your npm version, and then `npm audit` to get more info.
/usr/local/bin/firebase -> /usr/local/lib/node_modules/firebase-tools/bin/firebase

> @google-cloud/functions-emulator@1.0.0-beta.4 postinstall /usr/local/lib/node_modules/firebase-tools/node_modules/@google-cloud/functions-emulator
> node scripts/upgrade-warning


If you're using the Emulator via the Firebase CLI, you can
disregard this message.

If you're upgrading @google-cloud/functions-emulator, these
are the recommended upgrade steps:

1.  Stop the currently running emulator, if any:

        functions stop

2.  Uninstall the current emulator, if any:

        npm uninstall -g @google-cloud/functions-emulator

3.  Install the new version of the emulator:

        npm install -g @google-cloud/functions-emulator

If you have trouble after upgrading, try deleting the config
directory found in:

    ~/.config/configstore/@google-cloud/functions-emulator

Then restart the emulator. You can also check for any renegade
Node.js emulator processes that may need to be killed:

    ps aux | grep node

+ firebase-tools@3.19.3
added 540 packages in 25.989s
$ firebase login
(node:3736) ExperimentalWarning: The fs.promises API is experimental
? Allow Firebase to collect anonymous CLI usage and error reporting information? Yes

Visit this URL on any device to log in:
https://accounts.google.com/o/oauth2/auth?client_id=563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com&scope=email%20openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloudplatformprojects.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ffirebase%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&response_type=code&state=385007799&redirect_uri=http%3A%2F%2Flocalhost%3A9005

Waiting for authentication...

✔  Success! Logged in as <メールアドレス>
$ mkdir <プロジェクト名>
$ cd <プロジェクト名>
$ firebase init
(node:4160) ExperimentalWarning: The fs.promises API is experimental

     🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥     🔥🔥🔥     🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥
     🔥🔥        🔥🔥  🔥🔥     🔥🔥 🔥🔥       🔥🔥     🔥🔥  🔥🔥   🔥🔥  🔥🔥       🔥🔥
     🔥🔥🔥🔥🔥🔥    🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥   🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥
     🔥🔥        🔥🔥  🔥🔥    🔥🔥  🔥🔥       🔥🔥     🔥🔥 🔥🔥     🔥🔥       🔥🔥 🔥🔥
     🔥🔥       🔥🔥🔥🔥 🔥🔥     🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥 🔥🔥🔥🔥🔥🔥🔥🔥  🔥🔥     🔥🔥  🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥🔥

You're about to initialize a Firebase project in this directory:

  /Users/<ユーザー名>/workspace/<プロジェクト名>

? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choices. Database: Deploy Firebase Realtime Database Rul
es, Firestore: Deploy rules and create indexes for Firestore, Functions: Configure and deploy Cloud Functions, Hosting: Configure and deploy Firebase Hosting sites, Storage: Deploy Cl
oud Storage security rules

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Select a default Firebase project for this directory: <プロジェクト名> (<プロジェクト名>)

=== Database Setup

Firebase Realtime Database Rules allow you to define how your data should be
structured and when your data can be read from and written to.

? What file should be used for Database Rules? database.rules.json
? File database.rules.json already exists. Do you want to overwrite it with the Database Rules for <プロジェクト名> from the Firebase Console? Yes
✔  Database Rules for <プロジェクト名> have been downloaded to database.rules.json.
Future modifications to database.rules.json will update Database Rules when you run
firebase deploy.

=== Firestore Setup

Firestore Security Rules allow you to define how and when to allow
requests. You can keep these rules in your project directory
and publish them with firebase deploy.

? What file should be used for Firestore Rules? firestore.rules

Firestore indexes allow you to perform complex queries while
maintaining performance that scales with the size of the result
set. You can keep index definitions in your project directory
and publish them with firebase deploy.

? What file should be used for Firestore indexes? firestore.indexes.json

=== Functions Setup

A functions directory will be created in your project with a Node.js
package pre-configured. Functions can be deployed with firebase deploy.

? What language would you like to use to write Cloud Functions? TypeScript
? Do you want to use TSLint to catch probable bugs and enforce style? Yes
✔  Wrote functions/package.json
✔  Wrote functions/tslint.json
✔  Wrote functions/tsconfig.json
✔  Wrote functions/src/index.ts
? Do you want to install dependencies with npm now? Yes

> grpc@1.13.0 install /Users/<ユーザー名>/workspace/<プロジェクト名>/functions/node_modules/grpc
> node-pre-gyp install --fallback-to-build --library=static_library

[grpc] Success: "/Users/<ユーザー名>/workspace/<プロジェクト名>/functions/node_modules/grpc/src/node/extension_binary/node-v64-darwin-x64-unknown/grpc_node.node" is installed via remote

> protobufjs@6.8.8 postinstall /Users/<ユーザー名>/workspace/<プロジェクト名>/functions/node_modules/protobufjs
> node scripts/postinstall


> firebase-functions@1.1.0 postinstall /Users/<ユーザー名>/workspace/<プロジェクト名>/functions/node_modules/firebase-functions
> node ./upgrade-warning


======== WARNING! ========

This upgrade of firebase-functions contains breaking changes if you are upgrading from a version below v1.0.0.

To see a complete list of these breaking changes, please go to:

https://firebase.google.com/docs/functions/beta-v1-diff

npm notice created a lockfile as package-lock.json. You should commit this file.
added 520 packages from 503 contributors and audited 2595 packages in 29.882s
found 0 vulnerabilities


=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
✔  Wrote public/index.html

=== Storage Setup

Firebase Storage Security Rules allow you to define how and when to allow
uploads and downloads. You can keep these rules in your project directory
and publish them with firebase deploy.

? What file should be used for Storage Rules? storage.rules

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

✔  Firebase initialization complete!

firebaseのcliツールをセットアップしたは良いが、使わないかも・・・ 一旦firebase initで生成したファイルを削除しました。

フロントエンドの開発準備

$ npm install -g yarn
$ yarn -v
1.7.0
$ npm install -g vue-cli
$ vue -V
2.9.6

Gitリポジトリ

無料でプライベートリポジトリが作成できるBitbucketを選択しました。
普段使用しているGithubアカウントと区別するため、git configで明示的にuser情報を登録。

$ git config user.name "<ユーザ名>"
$ git config user.email "<メールアドレス>"

プロジェクト作成

基本的にはEnterで進めて行くが、最後の選択肢だけyarnを選択しました。

$ vue init webpack <プロジェクト名>

(node:34413) ExperimentalWarning: The fs.promises API is experimental
? Project name <プロジェクト名>
? Project description A Vue.js project
? Author <メールアドレス>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? Yes
? Should we run `npm install` for you after the project has been created? (recommended) yarn

   vue-cli · Generated "<プロジェクト名>".


# Installing project dependencies ...
# ========================

yarn install v1.7.0
info No lockfile found.
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
warning autoprefixer > browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
warning css-loader > cssnano > autoprefixer > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
warning css-loader > cssnano > postcss-merge-rules > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
warning css-loader > cssnano > postcss-merge-rules > caniuse-api > browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
warning jest > jest-cli > istanbul-api > istanbul-lib-hook@1.2.1: 1.2.0 should have been a major version bump
warning nightwatch > proxy-agent > socks-proxy-agent > socks@1.1.10: If using 2.x branch, please upgrade to at least 2.1.6 to avoid a serious bug with socket data flow and an import issue introduced in 2.1.0
warning webpack-bundle-analyzer > bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features!
[3/5] 🚚  Fetching packages...
[4/5] 🔗  Linking dependencies...
[5/5] 📃  Building fresh packages...
success Saved lockfile.
✨  Done in 29.22s.


Running eslint --fix to comply with chosen preset rules...
# ========================

yarn run v1.7.0
$ eslint --ext .js,.vue src test/unit test/e2e/specs --fix
✨  Done in 2.47s.

# Project initialization finished!
# ========================

To get started:

  cd <プロジェクト名>
  npm run dev
  
Documentation can be found at https://vuejs-templates.github.io/webpack
$ cd <プロジェクト名>
$ git commit -m "initial commit"

ローカルで起動

$ yarn dev

初期アプリケーション

firebaseのNode.JS用ライブラリを導入

$  yarn add firebase
yarn add v1.7.0
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
[3/5] 🚚  Fetching packages...
[4/5] 🔗  Linking dependencies...
warning "firebase > @firebase/storage@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/firestore@0.6.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/firestore > @firebase/firestore-types@0.5.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/functions@0.3.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/messaging@0.3.5" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/storage > @firebase/storage-types@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/database@0.3.4" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/functions > @firebase/messaging-types@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/auth > @firebase/auth-types@0.3.4" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/database > @firebase/database-types@0.3.2" has unmet peer dependency "@firebase/app-types@0.x".
[5/5] 📃  Building fresh packages...
success Saved lockfile.
success Saved 30 new dependencies.
info Direct dependencies
└─ firebase@5.3.0
info All dependencies
├─ @firebase/app-types@0.3.2
├─ @firebase/app@0.3.3
├─ @firebase/auth-types@0.3.4
├─ @firebase/auth@0.7.1
├─ @firebase/database-types@0.3.2
├─ @firebase/database@0.3.4
├─ @firebase/firestore-types@0.5.0
├─ @firebase/firestore@0.6.0
├─ @firebase/functions-types@0.2.0
├─ @firebase/functions@0.3.0
├─ @firebase/messaging@0.3.5
├─ @firebase/polyfill@0.3.3
├─ @firebase/storage-types@0.2.3
├─ @firebase/storage@0.2.3
├─ @firebase/webchannel-wrapper@0.2.8
├─ ascli@1.0.1
├─ bytebuffer@5.0.1
├─ colour@0.7.1
├─ dom-storage@2.1.0
├─ encoding@0.1.12
├─ firebase@5.3.0
├─ grpc@1.11.3
├─ isomorphic-fetch@2.2.1
├─ long@3.2.0
├─ node-fetch@1.7.3
├─ optjs@3.2.2
├─ promise-polyfill@7.1.2
├─ protobufjs@5.0.3
├─ whatwg-fetch@2.0.4
└─ xmlhttprequest@1.8.0
✨  Done in 31.10s.

VueFireを導入

$ yarn add vuefire
yarn add v1.7.0
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
[3/5] 🚚  Fetching packages...
[4/5] 🔗  Linking dependencies...
warning "firebase > @firebase/database@0.3.4" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/firestore@0.6.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/functions@0.3.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/messaging@0.3.5" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/storage@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/auth > @firebase/auth-types@0.3.4" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/database > @firebase/database-types@0.3.2" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/firestore > @firebase/firestore-types@0.5.0" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/functions > @firebase/messaging-types@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
warning "firebase > @firebase/storage > @firebase/storage-types@0.2.3" has unmet peer dependency "@firebase/app-types@0.x".
[5/5] 📃  Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ vuefire@1.4.5
info All dependencies
└─ vuefire@1.4.5
✨  Done in 9.60s.

CircleCIの設定

BitbucketのアカウントでCircleCIに新規登録し、Add Projectします。 言語でNodeを選択すると、config.ymlのテンプレが表示されるので、.circleci/config.ymlに保存し、Bitbucketリポジトリにpushします。
CircleCIの設定

# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2
jobs:
  build:
    docker:
      # specify the version you desire here
      - image: circleci/node:7.10
      
      # Specify service dependencies here if necessary
      # CircleCI maintains a library of pre-built images
      # documented at https://circleci.com/docs/2.0/circleci-images/
      # - image: circleci/mongo:3.4.4

    working_directory: ~/repo

    steps:
      - checkout

      # Download and cache dependencies
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          # fallback to using the latest cache if no exact match is found
          - v1-dependencies-

      - run: yarn install

      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
        
      # run tests!
      - run: yarn test

.circleci/config.ymlをプッシュした後、Add Projectの画面でBuildボタンを押したところ、ボタンのテキストが一瞬「Failed」に変わって、ビルドが始まらないトラブルに遭遇しました。
ProjectのFollow/Unfollowを繰り返したりして散々悩みましたが以下のようにpushし直したら無事CircleCI側でビルドが走りました。

$ git commit --amend
$ git push -f origin master

CircleCIの実行結果
今日はここまで。