SAP UI5 应用 index.html 里 data-sap-ui-resourceroots 指令的含义和作用

如下图所示:

<script id="sap-ui-bootstrap"
	src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
	data-sap-ui-theme="sap_bluecrystal"
	data-sap-ui-libs="sap.m, sap.ui.comp"
	data-sap-ui-bindingSyntax="complex" 
	data-sap-ui-compatVersion="edge"
	data-sap-ui-preload="async"
	data-sap-ui-resourceroots='{
		"sap.ui.demo.CombineLatest": "./"
	}'>
</script>

我刚学习 SAP UI5 时,对 data-sap-ui-resourceroots 的作用很是费解。

浏览我们开发的整个 SAP UI5 项目资源,无论是 Component.js:


还是视图的控制器:

还是视图的 id 本身,都包含了 sap.ui.demo.CombineLatest 的前缀:

如果我们把 index.html 里的 data-sap-ui-resourceroots 指令去掉:

会发现应用根本无法加载了,Chrome 开发者工具里报了很多资源文件无法加载的错误。

摘取其中一条错误消息出来分析。现在 Component.js 的加载路径为:

https://sapui5.hana.ondemand.com/resources/sap/ui/demo/CombineLatest/Component.js

显然,这个路径是继承自 index.html 里 id 为 sap-ui-bootstrap 里的 src 属性定义的 SAP UI5 库文件:

我们工程文件里的 Component.js, 其 id 为 sap.ui.demo.CombineLatest.Component:

SAP UI5 框架在加载时,将 id 转换成 url:

sap/ui/demo/CombineLatest/Component.js,

然后在其头部,拼接上来自 id 为 sap-ui-bootstrap 里的 src 属性定义的 SAP UI5 库文件的前缀:

https://sapui5.hana.ondemand.com/resources/

最后得到的路径:

https://sapui5.hana.ondemand.com/resources/sap/ui/demo/CombineLatest/Component.js

显然,这个路径是错误的。因为 Component.js 仅仅存在于我们工程自身。

因此需要使用 data-sap-ui-resourceroots 告诉 SAP UI5 加载器,如果遇到前缀为 sap.ui.demo.CombineLatest 的本地资源文件,不要使用 sap-ui-core.js 的前缀即 https://sapui5.hana.ondemand.com/resources,而是使用本地路径./

修改之后,资源加载成功,正确的路径应该是:http://localhost:3002/combine/Component.js

这个路径是怎么来的呢?

(1) Component.js 的 id 为 sap.ui.demo.CombineLatest.Component,因为 data-sap-ui-resourceroots 生效,将 sap.ui.demo.CombineLatest.Component 替换成 ./Component

(2) ./Component 替换成 URL:/Component.js

(3) ./之前的 url 为 localhost:3002/combine

得到最后的绝对路径去加载 Component.js:

http://localhost:3002/combine/Component.js

更多Jerry的原创文章,尽在:"汪子熙":

原文地址:https://www.cnblogs.com/sap-jerry/p/14889470.html