![](/img/trans.png)
[英]Angular CLI build using base-href and deploy-url to access assets on CDN
[英]What's the difference between --base-href and --deploy-url parameters of angular-cli tool
Angular 的文档告诉人们应该在 Angular 应用程序构建中使用--base-href
参数,以便将其部署在子文件夹中:
如果将文件复制到服务器子文件夹 append 构建标志
--base-href
并适当地设置<base href>
。例如,如果
index.html
位于服务器上的/my/app/index.html
,则像这样将基本 href 设置为<base href="/my/app/">
。
https://angular.io/guide/deployment
但是,angular-cli 具有--deploy-url
参数。 该工具的文档将其描述为:
URL 将部署文件的位置。
https://github.com/angular/angular-cli/wiki/build
当应用程序要部署在子文件夹中时,我已经看到使用--deploy-url
而不是--base-href
的解决方案。
#问题#
angular-cli 工具的--base-href
和--deploy-url
参数有什么区别? 我应该什么时候使用每一个?
在大多数情况下,base-href 就足够了。
请看这些帖子:
要将我的脚本放在“ /test/app1/script/ ”文件夹中,我使用以下命令:
ng build --prod --base-href /test/app1/ --deploy-url /test/app1/script/
因此,我的应用程序可在https://example.com/test/app1/访问,但我的 JS 脚本和 CSS 位于https://example.com/test/app1/script/目录中。
如果我想使用 /users 作为我的路由器应用程序基础和 /public 作为我资产的基础。
ng build --prod --base-href /users --deploy-url /public
有关详细示例,请参阅Shekhar Gulati 的博客...
这里的答案并不完全准确,已经过时,也没有给出完整的解释。
我应该什么时候使用每一种?
tl;dr一般使用--base-href
,因为--deploy-url
base href
的好处。 如果您需要 URL 与放置资源的位置不同,官方文档建议手动设置APP_BASE_HREF
(并且不同,例如将--base-href
设置为/public/
并将APP_BASED_HREF
为/users/
如果您将提供 Angular 文件在https://example.com/public/但您希望网络应用程序的 URL 为https://example.com/users/ )
angular-cli 工具的
--base-href
和--deploy-url
参数有什么区别?
上面我已经列出了 3 个不同之处。
正如您在问题中已经指出的那样, --base-href
<base href>
--base-href
在index.html
设置<base href>
(有关详细信息,请参阅Mozilla 文档,有关含义请参阅社区 wiki ),而--deploy-url
为相关前缀index.html
文件中的链接。
例如,以下index.html
片段:
<link rel="stylesheet" href="styles.HASH.css">
...
<script src="main.HASH.js" type="module"></script>
使用--deploy-url /public/
,将输出为:
<link rel="stylesheet" href="/public/styles.HASH.css">
...
<script src="/public/main.HASH.js" type="module"></script>
--deploy-url
似乎只是为链接添加前缀,所以如果你改为--deploy-url public
,输出将几乎无法使用:
<link rel="stylesheet" href="publicstyles.HASH.css">
...
<script src="publicmain.HASH.js" type="module"></script>
最后,如果您有使用相对链接到资产,如模板(HTML) header.component.html
包含<img src="assets/logo.jpg">
但是你用--deploy-url /public/
,该链接不会带有前缀,并且会给您一个损坏的图像。 如果<base href="/public/">
使用--base-href /public/
设置,这将起作用。
从 Angular v12 迁移到 Angular v14:
v12 之前
索引.html:
<base href="/"> // overriden by angular.json
package.json:
"start": "ng serve --base-href=/my-app/" // obsolete
v14 之后
angular.json:
"baseHref": "/" // used for finding .js files
app.module.ts:
providers: [{ provide: APP_BASE_HREF, useValue: '/my-app/' }, // used for routing
在 angular.json 中指定"deployUrl"
对我不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.