如何配置ui5-cli使UI5项目根路径自动加载index.html
Problem
I've just created my first SAPUI5/OpenUI5 project following the walkthrough documentation, using ui5-cli and NPM for project management. After starting the service with ui5 serve -o index.html, I have to access localhost:8080/index.html to view the project—visiting localhost:8080/ directly doesn't automatically redirect to index.html.
Here are my current configuration files:
package.json
{ "name": "appname", "version": "1.0.0", "description": "app description", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "ui5 serve -o index.html", "build": "ui5 build --all" }, "keywords": [ "keyword" ], "author": "", "license": "ISC", "dependencies": { "@openui5/sap.m": "^1.64.0", "@openui5/sap.ui.core": "^1.64.0", "@openui5/sap.ui.layout": "^1.64.0", "@openui5/sap.ui.unified": "^1.64.0", "@openui5/themelib_sap_belize": "^1.64.0" } }
ui5.yaml (generated by ui5 init)
specVersion: '1.0' metadata: name: appname type: application
Solution
To make localhost:8080/ automatically redirect to index.html, you need to add a redirect middleware to your UI5 CLI configuration. Follow these steps:
Install the redirect middleware
Run this command in your project root to addui5-middleware-redirectas a dev dependency:npm install --save-dev ui5-middleware-redirectUpdate your
ui5.yaml
Add aserversection to configure the redirect rule for the root path:specVersion: '1.0' metadata: name: appname type: application server: customMiddleware: - name: ui5-middleware-redirect afterMiddleware: compression configuration: paths: - path: / target: /index.htmlRestart the dev server
Stop your runningui5 serveinstance and restart it withnpm run devorui5 serve. Now accessinglocalhost:8080/will automatically loadindex.html.
Bonus tip: If you want the browser to open the root path directly when starting the server, you can update the dev script in package.json to:
"dev": "ui5 serve -o /"
This just changes the initial opened URL—you still need the redirect middleware to make the root path itself resolve correctly.
内容的提问来源于stack exchange,提问作者zouyi100

