iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 30
4
Modern Web

用30天深入Angular 5的世界系列 第 30

[技術支援-8] 產品發佈設定

將產品發佈到正式環境

  • 最簡單的方法是
    ng build
    
  • 將所有dist/資料夾底下的文件複製一份到伺服器上
  • 如果想順帶設置base href<base href="/my/app/">,則可加下面參數
    ng build --base-href=/my/app/
    
  • 若有使用Router功能,將所有找不到的頁面都導向index.html(下面會有詳細介紹)

優化我們的Angular專案

加上--prod參數,會能輸出優化過的檔案

ng build --prod

這個參數會為我們的專案做這些事情

  • 改使用AOT編譯:預先編譯而不是用JIT的方式
  • 開啟production mode: 可以讓網站執行更快,等同於下這個參數--environment=prod
  • Bundling: 將所有的所使用的library和許多應用綁在一起
  • 縮小檔案:刪除多餘的空白,註釋和可選的令牌。
  • Uglification:將變數名稱做混淆的動作。
  • 消除死代碼:刪除未引用的模塊和很多未使用的代碼

添加--build-optimizer可進一步減少檔案的大小

ng build --prod --build-optimizer

如果要使用惰性加載去載入部份的JS檔案,記得不要在需要被首先加載的模組裡面import要被惰性加載的元件,否則會在一開始就被載入。
AOT預設在編譯時會對ngModules做識別並且做惰性加載的設定。

善用bundles工具

source-map-explorer是一個很棒的bundles工具。可以將許多的js綑綁在一起。

首先先安裝

npm install source-map-explorer --save-dev

然後建構應用程式

ng build --prod --sourcemaps

在dist生成綑綁包

ls dist/*.bundle.js

運行管理器來生成這個被綑綁的檔案的分析圖

node_modules/.bin/source-map-explorer dist/main.*.bundle.js

產生的圖如下:

善用效能觀察工具

首推的當然就是google chrome囉!
這邊有相關的教學系列文:認識 Chrome 開發者工具
也推薦使用WebPageTest 來衡量自己網頁的速度

伺服器啟用Route功能的配置方法

Apache設定方式

添加一個重寫規則.htaccess

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

NGinx

使用前端控制器模式Web應用程序中try_files描述的方法 修改為:index.html

try_files $uri $uri/ /index.html;

IIS

添加一個重寫規則web.config

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/src/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

GitHub Pages

我們無法直接配置GitHub Pages服務器,但是可以添加一個404頁面。複製index.html到404.html。 它仍將作為404響應,但瀏覽器將處理該頁面並正確加載應用程序。從服務docs/上創建一個.nojekyll文件

Firebase hosting

添加一個重寫規則

"rewrites": [ {
  "source": "**",
  "destination": "/index.html"
} ]

上一篇
[技術支援-7] TypeScript設定
下一篇
[後記] 參賽心得
系列文
用30天深入Angular 5的世界31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
AlanShun
iT邦新手 5 級 ‧ 2018-01-18 00:53:03

感謝大大的分享~
恭喜30天完賽=ˇ=
GitHub Page可以使用這個
https://www.npmjs.com/package/angular-cli-ghpages

"deploy:github": "ng build --prod --build-optimizer --base-href=https://[username].github.io/[repository]/ && ngh"
https://zouyoushun.github.io/ngx-y2-player/
只要設定好--base-href然後下ngh就能deploy上去了/images/emoticon/emoticon01.gif

哇~謝謝分享!!其實我只有Apache的部份有實際用過...XD

我要留言

立即登入留言