base-href 跟專案發布後的路徑有關
一般來說,如果沒有特別設置就是 <base href="/">
,而發布後的網址會是 https://domain.com
有時候,在實際發布時會將專案部署於特定資料夾中(像是部署至 IIS 時需要設置虛擬目錄),如 /product
,預期發布後的網址會是 https:domain.com/product
。這時就會需要在 build
時指定部署後路徑,有以下幾種設置方法:
- CLI 指令執行
$ ng build --base-href /product/
- 於
index.html
中設置<base href='/product/'>
- 於
package.json
中設置--base-href
{
"name": "project",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --base-href /product/ --host 0.0.0.0",
"start:prod": "ng serve --base-href /product/ --prod",
"build": "ng build --base-href /product/",
"build:prod": "ng build --base-href /product/ --prod",
...
},
...
}
注意:前後都必須加入 ” / “,否則會找不到對應的資料夾( /product/
)
不管用上述何種方法,如果在本地端啟動(將方法一中的 build
改為 serve
),成功後則會顯示包含 base-href
的網址(如下),且專案各頁面相關的 script 都會發布到 /product
這個資料夾底下
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/product **
補充:如果要在打包時指定輸出路徑,可以至 angular.json
中修改 outputPath
{
...
"projects": { ... },
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/product",
"index": "src/index.html",
...
}
}
}
}