なになれ

IT系のことを記録していきます

MEAN and Cosmos DBをVisual Studio Team ServicesでAzure App Serviceにデプロイする

サンプルアプリの準備

MEAN構成のサンプルアプリとして以下を使用する
https://github.com/hi1280/angular-cosmosdb

前提条件

Azure CLI 2.0をインストールしている
https://docs.microsoft.com/ja-jp/cli/azure/install-azure-cli

Angular CLIをインストールしている

npm install -g @angular/cli

VSTSのプロジェクトが作られている
https://www.visualstudio.com/en-us/docs/setup-admin/team-services/sign-up-for-visual-studio-team-services

Cosmos DBの作成

以下のコマンドを実行する

# コマンドのオプションは環境に応じて適宜変更する  
az login
az group create -n my-heroes-db-group -l "Japan East"

# Cosmos DBをMongoDBのAPIで作成する
# Cosmos DBの名前が競合して作成できない場合、-nオプションの値を適宜変更する  
az cosmosdb create -n my-cosmos-heroes-example -g my-heroes-db-group --kind MongoDB

サンプルアプリとCosmos DBの連携

Cosmos DBの接続文字列を確認する

az cosmosdb list-connection-strings -n my-cosmos-heroes-example -g my-heroes-db-group --query "connectionStrings[0].connectionString"

example-environment.jsを接続文字列の内容に沿って修正する
このパラメータはサンプルアプリからCosmos DB(MongoDB)に接続する際の接続文字列に使われる
f:id:hi1280:20170730143854p:plain

example-environment.jsのファイル名をenvironment.jsに変更する

ローカルでアプリを起動する
# Angular CLIのビルド実行
npm run build

# Node.jsの実行
npm start

http://localhost:3000をブラウザで開く

Azure App Serviceの作成

az group create --location "Japan East" --name myResourceGroup 

# FREEプランで作成
az appservice plan create --name my-app-heroes-plan --resource-group myResourceGroup --sku FREE
az webapp create --name my-app-heroes-example --resource-group myResourceGroup --plan my-app-heroes-plan

# node.jsのバージョン指定
az webapp config appsettings set -g myResourceGroup -n my-app-heroes-example --settings WEBSITE_NODE_DEFAULT_VERSION=6.11.1

Visual Studio Team Services(VSTS)との連携とデプロイ

プロジェクトをVSTSにPushする

プロジェクトルートで以下のコマンドを実行する

# 既存のgitリポジトリを削除
rm -fR .git

# gitのローカルリポジトリに対する操作
git init
git add .
git commit -m "initial commit"

# gitのリモートリポジトリに対する操作
# xxxxxは任意
git remote add origin https://xxxxx.visualstudio.com/_git/my-app-heroes-example
git push -u origin --all
VSTS上でプロジェクトのビルド定義をする

ビルドタスクは以下の通りに定義する

Get Sources

  • This Projectを選択する
  • 該当のリポジトリとブランチを選択する

npmパッケージをインストール

  • Add Taskをクリックし、npmを追加する
  • installコマンドを選択する

Angular CLIのビルド実行

  • Add Taskをクリックし、npmを追加する
  • customコマンドを選択する
  • Command and argumentsrun buildと入力する

サーバのnpmパッケージをインストール

  • Add Taskをクリックし、npmを追加する
  • installコマンドを選択する
  • Working folder with package.jsondistと入力する

成果物を公開する

  • Add Taskをクリックし、Publish Build Artifactsを追加する
  • Path to Publishdistと入力する
  • Artifact Namedistと入力する
  • Artifact TypeServerを選択する

f:id:hi1280:20170730230357g:plain

VSTS上でプロジェクトのリリース定義をする

リリースタスクは以下の通りに定義する

Artifact

  • ビルドのArtifactの最新を選択する

Azure App Serviceにデプロイする

  • Run on agentの+マークをクリックし、Azure App Service Deployを追加する
  • Azure subscription及びApp Service nameを適宜選択する
  • Package or folder$(System.DefaultWorkingDirectory)/my-app-heroes-example-build/distと入力する
  • Generate Web.configにチェックをつける
  • Web.config parameters-Handler iisnode -NodeStartFile index.js -appType nodeと入力する
  • Publish using Web Deployにチェックをつける

f:id:hi1280:20170730230455g:plain


VSTS上からビルド及びリリースを実行した後に、Azure App ServiceのURLを開くとアプリが実行できる

Visual Studio CodeでTypeScriptを書くときのオススメ設定

2018/12/10 コードフォーマットに関してPrettierの情報を追記


TypeScriptにある便利機能をVisual Studio Code(以下、VSCode)がいい感じに可視化してくれるので、この二つの組み合わせは非常に良いです。
その中でも個人的に良いと思った機能と設定方法を紹介します。

なお、動作確認は以下のバージョンで行なっています。

Node.js: 6.11.1
TypeScript: 2.4.2
VSCode: 1.14.2
tslint: 5.5.0

誤りを教えてくれる

Compiler Optionsの--strictを有効にする

https://www.typescriptlang.org/docs/handbook/compiler-options.html

--strictを有効にすることで、Compiler Optionsの以下を全て有効にしたことと同様になります。

  • --noImplicitAny
  • --noImplicitThis
  • --alwaysStrict
  • --strictNullChecks

この中でも、--strictNullChecksはコード中のnullやundefinedを極力なくすことができるので良いです。

let strA: string = "str";
// error TS2322: Type 'null' is not assignable to type 'string'.
strA = null;

let strB: string | null = "str";

strB = null;

let objA: {x: string,y?: number} = {x: "str"};

// error TS2532: Object is possibly 'undefined'.
objA.y.toString();

if(objA.y) {
  objA.y.toString();
}

nullを代入するには、nullを許容する型にする必要あり。
オブジェクトでオプショナルなパラメータを定義した場合など、undefinedが許容される可能性がある場合に そのままパラメータにアクセスしようとすると、エラーになる。
if文で存在チェックをすると、エラーが解消される。

便利だし、安全です。

VSCode上でもいい感じに可視化してくれます。
f:id:hi1280:20170723234156p:plain

設定方法

下記コマンドでtsconfig.jsonを新規作成すると楽です。

tsc --init

strictが有効な設定でtsconfig.jsonが作られます。

tslintとvscode-tslintを使う

tslintはTypeScript用の静的解析ツールです。
vscode-tslintはtslintのVSCode拡張機能です。tslintの結果をVSCode上にいい感じに出力してくれます。
f:id:hi1280:20170723214438p:plain

設定方法

tslintのインストール方法

npm install -g tslint

vscode-tslintのインストール先
https://marketplace.visualstudio.com/items?itemName=eg2.tslint

tslintの設定

下記コマンドでtslint.jsonを新規作成すると楽です。

tslint --init

デフォルトのLintの設定が下記になるので、必要に応じて、ルールを個別に設定すれば良いと思います。
https://github.com/palantir/tslint/blob/master/src/configs/recommended.ts

tslintのルール一覧
https://palantir.github.io/tslint/rules/

正しく直してくれる

VSCodeのフォーマット機能を使う

VSCodeではTypeScriptを標準でサポートしていて、コードのフォーマット機能があります。 f:id:hi1280:20170723222825g:plain

設定方法

フォーマットの設定はVSCodeの設定から変更することができます。
f:id:hi1280:20170723224436g:plain


2018/12/10 追記
VSCodeのフォーマット設定は少し煩雑でどう設定していいのかわかりづらいです。
最近はPrettierを使うのがデファクトスタンダードのようです。

hi1280.hatenablog.com

誤りの追跡がしやすい

Debugger for Chromeを使う

Debugger for ChromeVSCode拡張機能です。Chrome上での実行に対して、VSCodeデバッグ機能が使えるようになります。
f:id:hi1280:20170723231934g:plain

設定方法

Debugger for Chromeのインストール先
https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome

launch.jsonの設定

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome",
      "url": "http://localhost:8080",
      "webRoot": "${workspaceRoot}"
    },
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome to local file",
      "file": "${workspaceRoot}/index.html"
    }
  ]
}

localにあるファイルを開く場合とurlにアクセスする場合の設定があります。


最後はTypeScript関係ないですが(汗
とりあえずVSCodeは機能が充実していて良いって話です。


2018/12/04 追記

VSCode+TypeScriptのCLI開発向け雛形構成を作りました hi1280.hatenablog.com

速習 TypeScript 第2版 速習シリーズ

速習 TypeScript 第2版 速習シリーズ