松本ぽんたのITブログ

入社4年目のIT社員のしがないブログ

Angularお勉強 ~その3~ Angularプロジェクトのファイル構成①

Angularプロジェクト

ng new コマンドで作ったAngularプロジェクトについて、
自動生成された各ファイルのロールをまとめる

                            • -
                            • -

srcフォルダ

Your app lives in the src folder. All Angular components, templates, styles, images, and anything else your app needs go here. Any files outside of this folder are meant to support building your app

Angularのアプリに必要なファイルは全てsrcフォルダ以下に配置する必要があるとのこと。
srcフォルダの外にあるファイル(package.json、angular.json、.gitignoreとか)はアプリではなくビルドを手助けする。

src
  L app
     L app.component.css
     L app.component.html
     L app.component.spec.ts
     L app.component.ts
     L app.module.ts
  L assets
     L .gitkeep
  L environments
     L environment.prod.ts
     L environment.ts
  L browserslist
  L favicon.ico
  L index.html
  L karma.conf.js
  L main.ts
  L polyfills.ts
  L styles.css
  L test.ts
  L tsconfig.app.json
  L tsconfig.spec.json
  L tslint.json
appコンポーネント、appモジュール

app.componentから始まるファイル群(css、html、specs.ts、ts)は、アプリのルートになるコンポーネントを構成している要素。
tsはおそらくタイプスクリプトの略。。
それぞれテンプレート(HTML)とそのスタイル(CSS)とロジック(TS)と単体テスト(SPEC.TS)。

Defines AppModule, the root module that tells Angular how to assemble the application. Right now it declares only the AppComponent. Soon there will be more components to declare.

app.module.tsはアプリケーションを構成するコンポーネント群とかを定義しとく場所と思っとけばいい?(自信ない・・)
自動生成された他のファイルを見るとindex.html内のapp-rootタグがあってそれをapp.component.tsのselectorで定義している。
一方main.tsにapp.module.tsへの参照があって、app.module.tsは前述のとおりコンポーネントを定義しているので、
順番としてはindex.html→main.ts→app.module.ts→app.component.tsの読み込みが入って、
selectorで定義したapp-rootがindex.htmlに埋め込まれるってことだと思ってるけど・・・。

assetsフォルダ

画像とか入れとく場所。
favicon.icoは対象外でよい?(´・ω・`)
ちなみにangular.jsonには

            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

と書いてあるので、アイコンもassetsフォルダに入れてまとめてしまえよと思ったり・・

environments

This folder contains one file for each of your destination environments, each exporting simple configuration variables to use in your application. The files are replaced on-the-fly when you build your app. You might use a different API endpoint for development than you do for production or maybe different analytics tokens. You might even use some mock services. Either way, the CLI has you covered.

宛先環境ごとに1つのコンフィグファイルを置いとく場所。
この場合environment.prod.tsとenvironment.tsの2つあるのでprod環境用とノーマル環境用ってことかな?
(prodはproductionの略で製品版って意味?)
ng buildコマンドでビルドする時に--prodオプションをつけるとenvironment.tsとprod.tsを置き換えてくれるらしい。
どう置き換えるかの定義はangular.jsonにかかれてるとのこと。↓

"configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],

肝心のenvironment.tsファイルには定数(constだしあってるよね?)が定義されていて、これをアプリ内で使えるらしい。

>src/environments/environment.ts
export const environment = {
  production: false
};

APIのキーとかを開発用とリリース用で使い分けたいときとかに使える機能の模様。。
確かにskyway使ってWebRTCした時のAPIキーの制御とかはDB使ってたし、それと比べたら便利かも??
2つの環境ファイルの使い分けはangular.json見る感じ結構がっつり定義しているように見えるのだけど、
これ環境ごとにファイル3つ、4つ用意しとくって出来るのだろうか・・・。
できるのか知らんけどAngularで出来てるアプリはこの変数を適当に変えたら製品版じゃない機能使えたりするのか?( ゚Д゚)

browserslist

異なるフロントエンドツール間でターゲットブラウザを共有するための定義を各ファイル。
デフォルトの定義はこんな感じ

# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For IE 9-11 support, please uncomment the last line of the file and adjust as needed
> 0.5%
last 2 versions
Firefox ESR
not dead
# IE 9-11

autoprefixerと呼ばれるベンダープレフィックスやらを対象ブラウザ向けにあれこれするツールに対して使われている模様。
(autoprefixerにはあまり詳しくない・・)
詳しい追加ルールは
GitHub - browserslist/browserslist: 🦔 Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-preset-env
を見てね。。とのこと。
例によってIEが若干はぶられている。

index.html
The main HTML page that is served when someone visits your site. 
Most of the time you'll never need to edit it. 
The CLI automatically adds all js and css files when building your app so you never need to add any <script> or <link> tags here manually.

Webサイトにアクセスしたときに最初に表示されるindexさん。
you'll never need to edit itって書いてあるけどほとんどの人はAngularアイコン外すために一度は編集するんじゃないですかね・・・。
コンポーネントのJSやらCSSやらは自動でリンクが張られるので人がスクリプトタグやら貼る必要はないよとのこと。
前使った時はbootstrapのリンクを直貼ってましたすみません。( ゚Д゚)

karma.conf.js

JavaScript単体テストツールのKarmaさんのコンフィグファイル(使ったことないけど)
詳しい定義とかはここを見てねとのこと。
Karma - Configuration File
単体テストはng testコマンドで起動する。

main.ts

The main entry point for your app. Compiles the application with the JIT compiler and bootstraps the application's root module (AppModule) to run in the browser. You can also use the AOT compiler without changing any code by appending the--aot flag to the ng build and ng serve commands.

アプリのメインエントリーポイント。

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

↑が気になっていてbootstrapってCSSフレームワーク?それとも別のことを言ってる?
わかり次第追記するかも・・

JITとかAOTとか意味わかんねぇって方は下記が詳しかったのでリンク張っておきます。(というか自分もわかってない)
qiita.com

polyfills.ts

Different browsers have different levels of support of the web standards. Polyfills help normalize those differences. You should be pretty safe with core-js and zone.js, but be sure to check out the Browser Support guide for more information.

ブラウザの違いを吸収するための仕組み?
正直説明呼んでもよくわからなかった。
polyfillsってポリマーのやつ?
ファイルの方には下記のように書いてある。

/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
*/

アプリに必要なpolyfillsを書いてね!
ZoneJS を読み込む前に適用されるブラウザーポリフィルと、ZoneJSの後でメインアプリより前にインポートされるアプリケーションインポートの2つが定義できるよ!
いまいまの設定は”まともな”ブラウザ用になっているよ!(IE除く)
もっと詳しいことは
https://angular.io/docs/ts/latest/guide/browser-support.html
を読んでね!

とのこと。
正直今までのファイルの中で一番意味不明だった。

styles.css

グローバルに適用するスタイルを記述する場所。
Angularは基本的にコンポーネント内で閉じたCSSを利用するけど、
それでも全体で統一感だしたいところとかをここに記述する。
angular.jsonのstylesでここが指定されていて、stylesは配列なので
例えば全体をBootstrapベースにしたいときとかは追加でbootstrapのCSSの場所とかを追加してやるとグローバルに定義できる。

test.ts


This is the main entry point for your unit tests. It has some custom configuration that might be unfamiliar, but it's not something you'll need to edit.

テスト時のエントリーポイント。
基本編集しなくてよいらしい。
中を見ると

const context = require.context('./', true, /\.spec\.ts$/);

とあってテストファイルの登録とかしているっぽい。

tsconfig.{app|spec}.json

TypeScriptコンパイラに対する設定で、アプリ用とテスト用の2つがある。
中身を見ると、例えばappは下記の定義がある。

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": []
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

多分本体のtsconfig.json追記する形でアプリ用の設定(テスト用ファイルのexcludeとか)を行っている模様。

tslint.json

Additional Linting configuration for TSLint together with Codelyzer, used when running ng lint. Linting helps keep your code style consistent.

リンターの設定。
ng lintで実行されるTS Lintの設定を書く。
こっちも本チャンの設定は"../tslint.json"に書いてあって、それを拡張している模様。


ここまででようやくsrc以下のファイルの説明が終了。
プラスしてルートフォルダ以下の他ファイルの説明もあるよ!(なげーわ)
Angularが大変なのってこういうところ?それともまだ上があるのか。。

The root folder

・・・長いので分割します。( ゚Д゚)