將Angular部屬至Firebase
說明
因我有使用Angular router,並且也有讀取相對路徑檔案的關係,在部屬至Github Page,網站很難正常運作,常常有幾頁OK,有幾頁卻出錯。
在研究之後發現Firebase根本為Angular而生,在使用後也發現,部屬透過CLI就能快速完成。
步驟
-
確定專案已經ng build –prod 過
-
你必須在 Firebase 上註冊一個 firebase 賬號。
-
npm install -g firebase-tools
在你Angular的root目錄那層開啟cli,並輸入以上指令即可。
- firebase login
若你的node.js版本較舊可能會出現錯誤,如果正確並第一次登入,會跳到瀏覽器請你選擇帳號登入。 若曾登入過,將會顯示
Already logged in as xxx@gmail.com
- firebase init
這步驟是最重要的喔,打了指令後,依序會出現以下問題
Are you ready to proceed? (Y/n)
請問你是否要繼續嗎,當然要選y
? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. (Press <space> to se
lect, <a> to toggle all, <i> to invert selection)
( ) Database: Deploy Firebase Realtime Database Rules
( ) Firestore: Deploy rules and create indexes for Firestore
( ) Functions: Configure and deploy Cloud Functions
( ) Hosting: Configure and deploy Firebase Hosting sites
>( ) Storage: Deploy Cloud Storage security rules
( ) Emulators: Set up local emulators for Firebase features
如果跟我一樣只是靜態網頁的架站,就選hosting,用上下鍵移動到該選項後按空白鍵,接著按下enter
Please select an option: (Use arrow keys)
> Use an existing project
Create a new project
Add Firebase to an existing Google Cloud Platform project
Don't set up a default project
這邊是問你說,你在本地端這個Angular的專案,有對應Firebase上面的專案了嗎? 建議先在Firebase上面建好對應專案後,選擇Use an existing project。
=== 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)
這邊請輸入你angular build好後的目錄,例如:
*dist/my-project-name *
? Configure as a single-page app (rewrite all urls to /index.html)? (y/N)
因angular routing問題,這個建議選擇y
? File dist/judge/index.html already exists. Overwrite?
這會覆蓋你建立好的index.html,因此選擇No
- firebase deploy
第四步驟都沒碰到問題,這步驟就照打你的網站就會出現於: https://{Your project’s name}.web.app
在console也會出現網址的提醒:
Project Console: https://console.firebase.google.com/project/{Your project's name}/overview
Hosting URL: https://{Your project's name}.web.app
可能會碰到的問題
- Node.js版本問題:一言不合就去練舞室啊!沒有啦,當我輸入 firebase login 指令時,出現錯誤,但在我乖乖升級電腦node.js版本後,就沒這問題了。
Comments