Posted on Leave a comment

[技術支援-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 來衡量自己網頁的速度

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

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"
} ]
Leave a Reply